简体   繁体   中英

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. 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.

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). If those lines are the entire program and you only want to play an mp3 , change your code to:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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