使用PyAudio和NumPy同时录制和播放音频

3

目前我可以录制音频并将其保存为NumPy数组。我需要的是在录制音频后,我想能够再次录制,但同时播放此NumPy数组。

import pyaudio
import numpy

CHUNK = 1024
WIDTH = 2
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=CHUNK) 

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(numpy.fromstring(data, dtype=numpy.int16))

numpydata = numpy.hstack(frames)

stream.stop_stream()
stream.close()

p.terminate()

如果您不坚持使用PyAudio,可以使用sounddevice.rec()sounddevice.playrec(),请参见https://python-sounddevice.readthedocs.io/en/0.3.12/usage.html#simultaneous-playback-and-recording(完全披露:我是作者)。 - Matthias
1个回答

0

你可以使用线程。请前往官方文档这里了解更多信息。我不太擅长录制和播放音频,所以我只创建了一个模板,应该适用于你。

这是我的示例:

from threading import Thread

def record():
  #Put your recording function here
def play():
  #Put your playing function here

Thread(target = record).start()
Thread(target = play).start()   
#These two start the two functions at the same time. If you want to only run the play
#function after it runs the record function once, you could do something like this:

这是更好的选择:

from threading import Thread

def record():
  #Put your recording function here
def play():
  #Put your playing function here

while recorded!=True
  Thread(target = record)
  recorded=True

Thread(target = record).start()
Thread(target = play).start()

在第二个例子中重复最后两行,您可以添加一个whilefor循环。如有疑问,请随时在评论中提出。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接