如何使用Python同时播放两个声音?

2024-04-25 23:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个循环系统(灵感来源于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,并没有将它们分层。再说一次,我希望能够同时播放多种声音。谢谢你的帮助!你知道吗


Tags: of声音timesleepsdrecordfsaudio
1条回答
网友
1楼 · 发布于 2024-04-25 23:29:02

你试过多线程解决方案吗?你知道吗

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

相关问题 更多 >