用 Pygame 播放音乐不可靠 [英] Playing music with Pygame unreliable
问题描述
我正在尝试编写一个简单的程序来使用 Pygame 播放音乐文件.我的脚本在下面.
I'm trying to write a simple program to play music files with Pygame. My script is below.
import pygame
import sys
import time
FRAMERATE = 30
if len(sys.argv) < 2:
sys.exit(2)
filename = sys.argv[1]
clock = pygame.time.Clock()
pygame.init()
pygame.mixer.init(frequency=44100)
pygame.mixer.music.load(filename)
print "%s loaded!" % filename
pygame.mixer.music.play(1)
while pygame.mixer.music.get_busy():
clock.tick(FRAMERATE)
但是我遇到了一些令人费解的问题."[File name] loaded!"
消息总是打印出来,但有时它永远不会进入循环并立即退出.如果我检查 pygame.mixer.music.get_busy()
的状态,它在 pygame.mixer.music.play(1)
命令后立即显示为 false.这不规律地发生;我只是尝试在不更改代码的情况下运行该程序,让它运行一次,然后立即遇到此问题.有谁知道是什么导致了这些看似随机的播放问题?
But I'm having some puzzling problems. The "[File name] loaded!"
message always prints, but sometimes it never enters the loop and exits immediately. If I check on the status of pygame.mixer.music.get_busy()
, it appears to be false immediately after the pygame.mixer.music.play(1)
command. This happens erratically; I just tried running the program with no changes to the code, having it work once and encounter this problem once right afterward. Does anyone know what could be causing these seemingly random playback problems?
推荐答案
我想这是因为实际的音乐播放是在另一个线程上进行的,所以有时在您第一次调用 get_busy 时还没有开始播放()
.
I imagine this is because the actual music playback is happening on another thread, so it sometimes hasn't finished starting at the point you first call get_busy()
.
如果是这样的话,这似乎是 pygame 或 SDL_mixer(pygame 使用的)中的一个错误.
If that's the case, it seems like a bug in either pygame or SDL_mixer (which pygame uses.)
作为检查音乐完成情况的另一种方法,您可以让 pygame 在音乐结束时为您提供一个事件并进行检查.像这样:
As an alternative way of checking for music completion, you can get pygame to give you an event when the music finishes and check for that. Like this:
pygame.mixer.music.set_endevent(pygame.USEREVENT)
quit = False
while not quit:
clock.tick(FRAMERATE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit = True
if event.type == pygame.USEREVENT:
print "Music ended"
quit = True
这篇关于用 Pygame 播放音乐不可靠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!