Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - How to get out of the while loop in Pygame when after playing the music?

I have the code down below actually what I want that when one the music get finished it should get out of the while loop automatically. But it isn't getting out of that and if I remove that while loop the song is not getting played.

from pygame import mixer 
    
def mplayer(name): 
    '''  for playing music  '''
    mixer.init() 
    mixer.music.load(name)
    mixer.music.set_volume(0.7) 
    mixer.music.play()

mplayer('welcome.mp3')
while True:
    continue

Is there any way that once the music is finished than it should get out the loop?

question from:https://stackoverflow.com/questions/65869913/how-to-get-out-of-the-while-loop-in-pygame-when-after-playing-the-music

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use mixer.music.get_busy() to test test if any sound is being mixed.

from pygame import mixer

def mplayer(name): 
    '''  for playing music  '''
    mixer.init() 
    mixer.music.load(name)
    mixer.music.set_volume(0.7) 
    mixer.music.play()

mplayer('welcome.mp3')

while mixer.music.get_busy():
    
    # you may have to handle the events here 
    # pygame.event.pump()
    # [...]
    
    pass

Note, you may need to handle the events in the loop that is waiting for the music to finish. See pygame.event.get() respectively pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.


PyGame has 2 different modules for playing sound and music, the pygame.mixer module and the pygame.mixer.music module. This module contains classes for loading Sound objects and controlling playback. The difference is explained in the documentation:

The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.

If pygame.mixer.music doesn't work for you try pygame.mixer.music:

from pygame import mixer

def mplayer(name): 
    '''  for playing music  '''
    mixer.init()
    my_sound = mixer.Sound(name)
    my_sound.set_volume(0.7) 
    my_sound.play(0)

mplayer('welcome.mp3')

while mixer.get_busy():

    # you may have to handle the events here 
    # pygame.event.pump()
    # [...]
    
    pass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...