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

时间:2016-08-10 16:27:11

标签: python numpy audio talkback

我试图创建一个程序来立即回复。我似乎无法让它发挥作用。有些网站说使用LAUNCHER阵列,但我不知道如何。

numpy
  

回溯(最近一次呼叫最后一次):文件" SoundTest.py",第24行,在myrecording = sd.play(myarray,fs,channels = 2)第2170行,在check_data dtype = _check_dtype( data.dtype)文件" /home/lordvile/.local/lib/python2.7/site-packages/sounddevice.py" ;,第2316行,在_check_dtype中引发TypeError('不支持的数据类型: ' + repr(dtype))TypeError:不支持的数据类型:' string32768'

2 个答案:

答案 0 :(得分:2)

下面是“ PyAudio”和“ Sounddevice”的示例,用于同时记录和播放。对我来说,最重要的是将输入和输出设备显式设置为有效值。因此,我为两个示例都包括了声音设备的打印。

声音设备:

与PyAudio相比,它的魅力十足。至少对我而言,声音设备为同时进行音频记录和播放提供了稳定的界面。尽管有一些控制台输出抱怨输入/输出上溢/下溢,但记录/回放会重新生成,最终我会得到流畅的“回声”。

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()

答案 1 :(得分:1)

不确定您是否需要使用pyaudio,但以下是使用sounddevice的示例。

下面的示例根据变量#seconds记录来自duration的麦克风的音频,您可以根据自己的要求进行修改。

使用标准音频输出(扬声器)播放相同的内容。

有关此here

的更多信息

工作代码

import sounddevice as sd
import numpy as np
import scipy.io.wavfile as wav

fs=44100
duration = 10  # seconds
myrecording = sd.rec(duration * fs, samplerate=fs, channels=2, dtype='float64')
print "Recording Audio for %s seconds" %(duration)
sd.wait()
print "Audio recording complete , Playing recorded Audio"
sd.play(myrecording, fs)
sd.wait()
print "Play Audio Complete"

<强>输出

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Recording Audio for 10 seconds
Audio recording complete , Playing recorded Audio
Play Audio Complete
>>>