同时使用pyaudio播放和录制声音 [英] Play and record sound using pyaudio simultaneously

查看:985
本文介绍了同时使用pyaudio播放和录制声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序以立即回覆.我似乎无法正常工作.一些网站说使用numpy数组,但我不知道如何.

I'm trying to create a program to talk back at once. I can't seem to get it to work. Some websites say use numpy arrays but I don't know how.

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)

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

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"用于同时记录和播放的示例.对我而言,最重要的是将输入和输出设备显式设置为有效值.因此,我为两个示例都包括了声音设备的打印.

Below are examples for both 'PyAudio' and 'Sounddevice' for simultaneous recording and playback. The most important thing for me was to explicitly set the input and output devices to a valid value. Hence, I included printing for sound devices for both examples.

声音设备:

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

Works like a charm compared to PyAudio. At least for me, sounddevice offers a stable interface for simultaneous audio recording and playback. Though there are a few console outputs complaining about a input/output over-/underflow, the record/playback regenerates and eventually I get a fluently working 'echo'.

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]输入溢出".我不知道为什么它总是会引发此错误,但是您可以自己尝试一下.

This code should(?) work. For me it does not work consistently. It already worked for about a minute once but usually I get the Error: "OSError: [Errno -9981] Input overflowed". I don't know why it always throws this error, but feel free to try it out yourself.

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

这篇关于同时使用pyaudio播放和录制声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆