繁体   English   中英

如何让pygame在播放一首歌后退出

[英]How to get pygame to quit after playing a song

我正在尝试使用本教程在我的脚本中运行 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()

这首歌播放得很好,但控制台中从未打印过“完成”。 程序停留在循环中......如何修复它? 谢谢

编辑:我发现了这个,它运行良好,有一首 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()

您对提供的两个示例有几个问题。

第一的:

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()

请参阅此答案以供参考

为您的循环设置一个变量,然后检查 mix.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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