如何使用Python一次播放两种声音?

时间:2019-08-25 04:58:55

标签: python audio python-sounddevice

我正在寻找一个循环系统(受Marc Rebillet的启发,将其签出),并且正在努力让自己播放2种声音。

我已经开始使用sounddevice,因为它是我发现的第一个音频模块,但是我不确定是否有其他一次可以更好地工作。

import time

def record(duration): # records a few seconds of audio
    print('recording in:')
    print('3')
    time.sleep(1)
    print('2')
    time.sleep(1)
    print('1')
    time.sleep(1)
    print('recording')
    record = sd.rec(int(duration * fs), samplerate=48000, channels=2)
    sd.wait()
    print('done\n\n')
    return record

duration = 3.5  # seconds

recordOne = record(duration)
recordTwo = record(duration)

while True: # repeats both pieces of audio
    sd.play(recordOne, fs)
    sd.play(recordTwo, fs)
    sd.wait()

此代码最终仅播放recordTwo,并且不会将它们彼此叠加。同样,我希望能够同时播放多种声音。谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您尝试过多线程解决方案吗?

import time
import threading


def record(duration): # records a few seconds of audio
    print('recording in:')

    for t in range(3, 0, -1):
        print(t)
        time.sleep(1)

    print('recording')
    print("mock record process...")
    start = time.time()
    time.sleep(10)
    print(f'done, {time.time() - start} seconds total.\n\n')
    return record


duration = 3.5  # seconds
recordOne = record(duration)
recordTwo = record(duration)


def play(record_piece):
    print("paly the sound")
    time.sleep(duration)


while True: # repeats both pieces of audio
    t1 = threading.Thread(target=play, args=(recordOne,))
    t2 = threading.Thread(target=play, args=(recordTwo,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

或者您可以尝试找到一些可以在播放前将两个音轨组合在一起的库。

我阅读了sounddevice的文档,它提供了一种播放方法,您尝试过吗?

playback

enter image description here