python-同时播放不同音量的音频样本

时间:2019-09-23 00:14:00

标签: python audio pygame volume simultaneous

我正在尝试使用python在Raspberry Pi上同时播放不同音量的音频样本:

from time import sleep
import threading
import pygame

def play(sample,volume):
    sample.set_volume(volume)
    sample.play()

pygame.init()
pygame.mixer.init()
sound = pygame.mixer.Sound('/home/pi/Desktop/sample.wav')
thr=threading.Thread(target=play,args=([sound,1]),kwargs={})
thr.start()
sleep(1)
thr=threading.Thread(target=play,args=([sound,0.5]),kwargs={})
thr.start()
sleep(1)
thr=threading.Thread(target=play,args=([sound,0.25]),kwargs={})
thr.start()
sleep(1)
thr=threading.Thread(target=play,args=([sound,0.1]),kwargs={})
thr.start()
sleep(5)

,但在此示例中,我在上次播放的样本上存在滞后。 我也想拥有8个频道的8个样本。

此代码有什么问题? 有更好的方法或库可以实现此目的?

编辑
我尝试使用频道,但播放音效2时仍然有滞后感

from time import sleep
import pygame

pygame.mixer.init()
channel1 = pygame.mixer.Channel(0)
channel2 = pygame.mixer.Channel(1)

sound1 = pygame.mixer.Sound('piano.wav') #duration 4s
sound2 = pygame.mixer.Sound('kick.wav') #duration <1s

channel1.play(sound1)
channel2.play(sound2)
sleep(0.25)
channel2.stop()
channel2.play(sound2)
sleep(0.25)
channel2.stop()
channel2.play(sound2)
sleep(0.25)
channel2.stop()
channel2.play(sound2)
sleep(5)

0 个答案:

没有答案