简体   繁体   English

音频没有播放 pygame

[英]The audio is not playing pygame

This is my code:这是我的代码:

from pygame import mixer

mixer.init()
mixer.music.load(r'C:\Users\mahad\Desktop\venvdir\analog.mp3')
mixer.music.play()
print("end")

I want to play a simple mp3 file.我想播放一个简单的 mp3 文件。 But it is not opening for some reason.但是由于某种原因它没有打开。 Can't figure out where I am wrong :(无法弄清楚我错在哪里:(

The play() call is non-blocking, ie if you immediately exit the application (as in your example) you will never hear the music. play()调用是非阻塞的,即如果您立即退出应用程序(如您的示例),您将永远听不到音乐。

If you try this:如果你试试这个:

from pygame import mixer
import time

mixer.init()
mixer.music.load(r'C:\Users\mahad\Desktop\venvdir\analog.mp3')
mixer.music.play()
time.sleep(5)
print("end")

you will at least hear five seconds of music.你至少会听到五秒钟的音乐。

In a proper game application you will have to start the music and then do other stuff - and not immediately exit the application.在适当的游戏应用程序中,您必须先播放音乐,然后再做其他事情——而不是立即退出应用程序。

Probably your program is exiting before the sound can be played (the play function is asynchronous).可能您的程序在可以播放声音之前退出( play功能是异步的)。 If those lines are the entire program and you only want to play an mp3 , change your code to:如果这些行是整个程序并且您只想播放mp3 ,请将代码更改为:

from pygame import mixer
from pygame import time

mixer.init()
mixer.music.load(r'C:\Users\mahad\Desktop\venvdir\analog.mp3')
mixer.music.play()
while mixer.music.get_busy():
    time.Clock().tick(10)

This will wait until the end of the audio stream.这将等到音频流结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM