簡體   English   中英

使用PyAudio和NumPy同時錄制和播放音頻

[英]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()

要在第二個示例中重復最后兩行,只需添加一個whilefor循環即可。 請隨時在評論中提問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM