目前,我可以录制音频并将其另存为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()
答案 0 :(得分:0)
您可以使用线程。有关更多信息,请参阅官方文档here。我不十分清楚录制和播放音频,因此,我刚刚创建了一个适合您的模板。
这是我的例子:
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
循环即可。请随时在评论中提问。