为什么pygame.event.wait会在大约20秒后停止音乐播放

2024-04-23 13:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以。。。我正在使用这个代码:

import pygame
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('computersong.mp3')
pygame.mixer.music.play()
pygame.event.wait()

但是音乐播放了20秒就停止了,我做错了什么


Tags: 代码importeventplay音乐initmusicload
2条回答

^{}从事件队列返回单个事件,但它不会等到音乐播放完毕。
您必须使用^{}并等待特定的时间:

pygame.time.wait(5000) # wait 5 seconds

另一种选择是使用^{}并在循环中等待音乐结束:

pygame.mixer.music.play()

clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
    pygame.event.poll()
    clock.tick(10)

你写的东西不清楚,但我猜你的computersong.mp3是20秒,它正在播放到结束并停止。假设是这种情况,并且您希望它重复,您可以尝试以下方法:

从pygame文档here中,您可以看到,如果希望重复歌曲,可以为循环参数指定一个值。如果你想让它继续循环直到你停止它,那么你就通过playloop=-1

pygame.mixer.music.play()

Start the playback of the music stream play(loops=0, start=0.0) -> None This will play the loaded music stream. If the music is already playing it will be restarted.

The loops argument controls the number of repeats a music will play. play(5) will cause the music to played once, then repeated five times, for a total of six. If the loops is -1 then the music will repeat indefinitely.

然后,您的代码需要继续执行其他操作。如果程序只是这样做然后退出,它当然会停止

相关问题 更多 >