如何使用Sounddevice仅播放一次音频文件?

2024-03-28 21:59:42 发布

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

我试图在通过麦克风录制响应时反复播放咔哒声。 我用playrec试过了,但从我读到的来看,你不应该重复使用它,它在循环中使用时也会产生一些奇怪的声音

所以我的想法是使用一个流,播放并录制n次声音。问题是,通过使用流,它只是无限期地重复我的点击声。有人知道如何在一次播放后停止吗

我尝试的代码:

import sounddevice as sd
import numpy  as np

print(sd.query_devices())

def callback(indata, outdata, frames, time, status):
    if status:
        print(status)

    t = (0 + np.arange(44100)) / 44100
    t = t.reshape(-1, 1)
    outdata[:] = np.sin(2 * np.pi * 1000 * t)

try:
    with sd.Stream(device=(1, 3),
                   samplerate=44100, blocksize=44100,callback=callback):
        print('#' * 80)
        print('press Return to quit')
        print('#' * 80)
        input()
except KeyboardInterrupt:
    parser.exit('')
except Exception as e:
    parser.exit(type(e).__name__ + ': ' + str(e))