gpt4 book ai didi

python - 尝试从麦克风录制并实时播放

转载 作者:太空狗 更新时间:2023-10-29 20:31:41 26 4
gpt4 key购买 nike

我正在尝试从我的麦克风记录数据,然后通过扬声器实时播放,但有一些延迟,但我遇到了一些问题。我选择使用 python 和 alsaaudio,可以找到我当前遇到问题的脚本 here .这适用于我目前所拥有的(不是延迟部分),但会产生一些咔哒声。 alsaaudio 文档有 this说:

The most common reason for problems with playback of PCM audio is that writes to PCM devices must exactly match the data rate of the device.

If too little data is written to the device, it will underrun, and ugly clicking sounds will occur. Conversely, of too much data is written to the device, the write function will either block (PCM_NORMAL mode) or return zero (PCM_NONBLOCK mode).

我似乎误解了文档,它说的是关于 write() 的:

PCM.write(data)

Writes (plays) the sound in data. The length of data must be a multiple of the frame size, and should be exactly the size of a period

我脚本中的一个句点是 160。

关于 read() 是这样说的:

In PCM_NORMAL mode, this function blocks until a full period is available, and then returns a tuple (length,data) where length is the number of frames of captured data, and data is the captured sound frames as a string. The length of the returned data will be periodsize*framesize bytes.

在我的脚本中,period_size*frame_size 也应该等于 160,但是当我打印长度(部分元组 read() 返回)时,我得到 940。显然我似乎没有传递正确数量的数据到 out.write(),但我不确定去哪里。我主要通过找到的示例将这段代码放在一起,我刚刚开始使用 alsaaudio/sound,试图将一些有趣的项目放在一起,所以我还不是很了解。

我还想通过麦克风进行现场录音,然后以 100 毫秒的延迟进行播放,因此评论了 time.sleep()。如果我取消注释,长度似乎从 940 反复变为 -32,最终导致 out.write() 抛出异常(数据不足)。

谁能告诉我如何(或者我的脚本有什么问题)实时录制和播放声音数据,并延迟 100 毫秒?

最佳答案

您不能使用 sleep(0.1) 将输出延迟 100 毫秒。您需要创建一个缓冲区来保存 100 毫秒的音频数据:

buf = []
while True:
l, data = inp.read()
buf.append(data)
if len(buffer)>=10:
out.write(buf[0])
del buf[0]

将 10 更改为某个会导致 100 毫秒延迟的数字。

关于python - 尝试从麦克风录制并实时播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7102676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com