启动main.py之后,我可以不断地在后台播放。

发布于 2025-01-19 17:18:15 字数 459 浏览 1 评论 0原文

 import pygame

 pygame.mixer.init()

 pygame.mixer.music.load("myFile.Mp3")

 pygame.mixer.music.play(-1) # note -1 for playing in loops

 # do whatever

 # when ready to stop do:

 pygame.mixer.pause()

 If you want to unpause:

 pygame.mixer.unpause()

我有一个关于 pygame 的问题! 我的 pygame 设置与上面的问题相同: 当我单击主要的 python 代码时,如何才能使其在后台持续播放而不是在启动 Main.py 时停止?

我尝试了上面的代码但是: 当我启动 Raspberry pi 4B 时它就会启动 但是当我单击 Main.py 时停止播放。

 import pygame

 pygame.mixer.init()

 pygame.mixer.music.load("myFile.Mp3")

 pygame.mixer.music.play(-1) # note -1 for playing in loops

 # do whatever

 # when ready to stop do:

 pygame.mixer.pause()

 If you want to unpause:

 pygame.mixer.unpause()

I have a question about pygame!
I have the same pygame setting as above my question:
When I click the main python code How can I keep this constantly playing in the background instead of stopping when I start Main.py?

I tried the code above but:
it It starts when I boot up the Raspberry pi 4B
but Stops playing when I click Main.py.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十六岁半 2025-01-26 17:18:15

就个人而言,我建议您使用弹奏模块,因为它很容易实现。运行pip安装弹奏,然后您可以在代码中包含此功能:

playsound("sound_file.mp3", block=False)

另外,您可以使用内置螺纹模块制作单独的线程来播放歌曲。我相信看起来像这样:

import threading
import pygame

pygame.mixer.init()

def play_song():
     pygame.mixer.music.load("my_song.mp3")

threading.Thread(target=play_song).start()

我个人推荐第一个。如果您想在循环中不断播放这首歌,则可以通过两者的组合来做类似的事情:

def play_song():
    while True:
        playsound("my_song.mp3", block=True)


song_thread = threading.Thread(target=play_song, name='Background_song')
song_thread.daemon = True  # Stops the song when the main file is closed
song_thread.start()

Personally, I’d recommend you use the playsound module, as it implements this pretty easily. Run pip install playsound, then you can include this in your code:

playsound("sound_file.mp3", block=False)

Alternatively, you could make a separate thread to play the song using the builtin threading module. I believe it would look like this:

import threading
import pygame

pygame.mixer.init()

def play_song():
     pygame.mixer.music.load("my_song.mp3")

threading.Thread(target=play_song).start()

I’d personally recommend the first one, however. If you want to play the song constantly in a loop, you could do something like this, with a combination of the two:

def play_song():
    while True:
        playsound("my_song.mp3", block=True)


song_thread = threading.Thread(target=play_song, name='Background_song')
song_thread.daemon = True  # Stops the song when the main file is closed
song_thread.start()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文