You can use PyAudio
to record audio and use np.frombuffer
to convert it into a numpy array.
import pyaudio
import numpy as np
from matplotlib import pyplot as plt
CHUNKSIZE = 1024 # fixed chunk size
# initialize portaudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=CHUNKSIZE)
# do this as long as you want fresh samples
data = stream.read(CHUNKSIZE)
numpydata = np.frombuffer(data, dtype=np.int16)
# plot data
plt.plot(numpydata)
plt.show()
# close stream
stream.stop_stream()
stream.close()
p.terminate()
If you want to record stereo instead of mono, you have to set channels
to 2
. Then you get an array with interleaved channels. You can reshape it like this:
frame = np.frombuffer(data, dtype=numpy.int16) # interleaved channels
frame = np.stack((frame[::2], frame[1::2]), axis=0) # channels on separate axes
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…