如何让pygame在播放完歌曲后退出

4 投票
2 回答
3986 浏览
提问于 2025-04-18 03:56

我正在尝试使用这个教程,在我的脚本中用pygame来替代Mplayer:

在代码中:

import pygame     
pygame.init()
song = pygame.mixer.Sound(my_song.ogg)
clock = pygame.time.Clock()
song.play()
while True:
   clock.tick(60)
pygame.quit()
print "done"   # not appears
exit()

音乐播放得很好,但控制台里从来没有打印出“done”。程序一直在循环中运行……

怎么解决这个问题呢?谢谢!

补充:我找到了解决办法,现在运行得很好,播放了一首10秒的歌曲:

import pygame
import time     
pygame.init()
song = pygame.mixer.Sound(son)
clock = pygame.time.Clock()
song.play()
while True:
  clock.tick(60)
  time.sleep(10)
  break
pygame.quit()
print "done"
exit()

2 个回答

0

为你的循环设置一个变量,然后检查mixer.music.get_busy()来判断你的循环是否应该停止。

from pygame import mixer

filename =  "mymusic.mp3"

x = mixer.init(frequency=44100)
mixer.music.load(filename)
mixer.music.play()

run = True
while run: 
    # ..do some stuff
    pos = mixer.music.get_pos() / 1000
    print('pos', pos)
    
    if mixer.music.get_busy() == False:
        run = False
10

你在提供的两个例子中有几个问题。

首先:

while True:
    clock.tick(60)

这个代码在任何情况下都是一个无限循环,不仅仅是在 pygame 中,它永远不会结束。

接下来:

while True:
    clock.tick(60)
    time.sleep(10)
    break

这个代码在第一次循环时就会 break,也就是说它会直接跳出循环,这等同于

clock.tick(60)
time.sleep(10)

所以它在播放 10 秒的歌曲时效果很好。

如果你想使用 pygame.mixer.Sound,你应该这样做,使用 Sound.get_length()

import pygame
import time     
pygame.init()
song = pygame.mixer.Sound("my_song.ogg")
clock = pygame.time.Clock()
song.play()
time.sleep(song.get_length()+1)  # wait the length of the sound with one additional second for a safe buffer
pygame.quit()
print "done"
exit()

pygame 推荐使用 mixer.music 来处理这类事情:

import pygame
import time     
pygame.init()
pygame.mixer.music.load("my_song.ogg")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
    continue
pygame.quit()
print "done"
exit()

可以参考这个答案

撰写回答