gpt4 book ai didi

python - 同时使用 pyaudio 播放和录制声音

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:49 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来立即回复。我似乎无法让它发挥作用。有些网站说使用 numpy 数组,但我不知道如何使用。

import pyaudio
import wave
import time
import multiprocessing as mp
import pyaudio
import numpy as np
import sounddevice as sd

fs = 44100
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
audio = pyaudio.PyAudio()
RECORD_SECONDS = 5
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
myarray = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
myarray.append(data)

myrecording = sd.play(myarray, fs, channels=2)

Traceback (most recent call last): File "SoundTest.py", line 24, in myrecording = sd.play(myarray, fs, channels=2) line 2170, in check_data dtype = _check_dtype(data.dtype) File "/home/lordvile/.local/lib/python2.7/site-packages/sounddevice.py", line 2316, in _check_dtype raise TypeError('Unsupported data type: ' + repr(dtype)) TypeError: Unsupported data type: 'string32768'

最佳答案

下面是同时录制和播放的“PyAudio”和“Sounddevice”的示例。对我来说最重要的是明确地将输入和输出设备设置为有效值。因此,我在这两个示例中都包含了声音设备的打印。

声音设备:

与 PyAudio 相比,它的工作方式就像一个魅力。至少对我来说,sounddevice 提供了一个稳定的接口(interface),可以同时进行音频录制和播放。尽管有一些控制台输出提示输入/输出上溢/下溢,但记录/播放会重新生成,最终我会得到流畅工作的“回声”。

import sounddevice as sd

fs = 44100

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

print(sd.query_devices())

try:
with sd.Stream(device=(0,1), samplerate=fs, dtype='float32', latency=None, channels=2, callback=callback):
input()
except KeyboardInterrupt:
pass

PyAudio:

这段代码应该(?)工作。对我来说,它并不能始终如一地工作。它已经工作了大约一分钟一次,但通常我会收到错误:“OSError:[Errno -9981]输入溢出”。我不知道为什么它总是抛出这个错误,但是你可以自己尝试一下。

import pyaudio
import json

FORMAT = pyaudio.paInt16
CHANNELS = 1
CHUNK = 1024
RATE = 44100

audio = pyaudio.PyAudio()

for i in range(audio.get_device_count()):
print(json.dumps(audio.get_device_info_by_index(i), indent=2))

stream = audio.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
output = True,
input_device_index = 0,
output_device_index = 1,
frames_per_buffer = CHUNK)

try:
frames = []
print("* echoing")
print("Press CTRL+C to stop")
while True:
data = stream.read(CHUNK)
frames.append(data)
if len(frames)>0:
stream.write(frames.pop(0),CHUNK)
print("* done echoing")
except KeyboardInterrupt:
stream.stop_stream()
stream.close()
audio.terminate()

关于python - 同时使用 pyaudio 播放和录制声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38878908/

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