播放音乐后如何退出Pygame中的while循环? [英] How to get out of the while loop in Pygame when after playing the music?

查看:50
本文介绍了播放音乐后如何退出Pygame中的while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码实际上是我想要的,当一首音乐完成时,它应该自动退出 while 循环.但它并没有摆脱这一点,如果我删除了 while 循环,歌曲就不会被播放.

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?

推荐答案

使用 mixer.music.get_busy() 测试是否有任何声音被混合.

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

注意,您可能需要处理等待音乐结束的循环中的事件.请参阅pygame.event.get() 分别 pygame.event.pump():

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 有 2 个不同的播放声音和音乐的模块,pygame.mixer 模块和 pygame.mixer.music 模块.该模块包含用于加载 Sound 对象和控制播放的类.文档中解释了差异:


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.

如果 pygame.mixer.music 对您不起作用,请尝试pygame.mixer.music:

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

这篇关于播放音乐后如何退出Pygame中的while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆