[英]Recording and playing audio simultaneously with PyAudio and NumPy
目前,我可以录制音频并将其另存为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()
您可以使用线程。 请转到官方文档以获取更多信息, 这里我不太了解如何录制和播放音频,因此我刚刚创建了一个适合您的模板。
这是我的示例:
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()
要在第二个示例中重复最后两行,只需添加一个while
或for
循环即可。 请随时在评论中提问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.