使用pygame +多重处理时出现音乐问题 [英] music problems when using pygame + multiprocessing
问题描述
我正在尝试运行一个脚本,该脚本将通过一个进程播放音乐.下面的代码是我的代码的精简版,但是足以复制该问题.如果我调用normal()
过程,我会听到音乐,所以我知道该过程是正确的,并且一切都已正确连接,但是,如果我使用多处理程序调用normal()
,则没有声音...它运行normal()
,但仍然没有音频 ...
I'm tring to run a script that would play music via a process. the code below is a stripped down version of my code but it's good enough to replicate the problem. If I call the normal()
procedure I hear music so I know the procedure is correct and everything is connected properly, however, if I call normal()
using multiprocessing there is no sound... It runs normal()
but still no audio...
有什么建议吗? 谢谢!
Any suggestions? thanks!
#!/usr/bin/python
#
# Import required Python libraries
import pygame, time
import multiprocessing as mp
localtime = time.asctime( time.localtime(time.time()) )
pygame.init()
cs = 0
def normal( cs ):
# main loop
try:
if cs == 1:
while cs == 1:
print " Starting normal function"
pygame.mixer.music.load('/home/user/scripts/music.mp3')
pygame.mixer.music.play()
time.sleep(20)
pygame.mixer.music.stop()
#return;
except KeyboardInterrupt:
print "Quit"
try:
print " Starting music"
# play here
cs = 1
p2 = mp.Process(target=normal, args=(cs,))
p2.start()
p2.terminate()
#normal( cs )
except KeyboardInterrupt:
print " Quit"
# End script
推荐答案
尝试一下:
pygame.mixer.music.load('/home/user/scripts/music.mp3')
pygame.mixer.music.play(-1,0) # add this args
sleep(20) #remove this line
mixer.music.stop() #remove this line
添加pygame.mixer.music.play(-1,0)
表示音乐将循环播放,直到您退出游戏为止,例如
Adding pygame.mixer.music.play(-1,0)
means that the music will play in loop until you quit the game e.g.
尝试删除sleep(20)
和mixer.music.stop()
.
还要检查您是否正在播放44.1kHz
MP3,默认的22050
频率有效,但是48kHz
mp3的播放速度不到一半-48000
或24000
可以工作.
Also check if you are playing a 44.1kHz
MP3, the default 22050
frequency works, but a 48kHz
mp3 plays in less than half speed - 48000
or 24000
works then.
或者根据采样率尝试这种方法:
Or try this approach depending on sample rate:
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
sound = pygame.mixer.Sound('/home/user/scripts/music.mp3').play()
或尝试此.
这篇关于使用pygame +多重处理时出现音乐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!