[英]Reading realtime audio data into numpy array
how can I read real-time audio into numpy array and use matplotlib to plot ?如何将实时音频读入 numpy 数组并使用 matplotlib 进行绘图?
Right Now I am recording audio on an wav
file then using scikits.audiolab.wavread
to read it into an array.现在我正在
wav
文件上录制音频,然后使用scikits.audiolab.wavread
将其读入数组。 Is there a way I could do this directly in realtime?有没有办法可以直接实时执行此操作?
You can use PyAudio
to record audio and use np.frombuffer
to convert it into a numpy array.您可以使用
PyAudio
录制音频并使用np.frombuffer
将其转换为 numpy 数组。
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
.如果要录制立体声而不是单声道,则必须将
channels
设置为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
There is a library called PyAudio
.有一个名为
PyAudio
的库。 You can use it to record in real-time.您可以使用它来实时记录。 Plus with the help of
numpy.fromstring()
and numpy.hstack()
, you can get the desired output.再加上
numpy.fromstring()
和numpy.hstack()
的帮助,您可以获得所需的输出。 Please note that the following snippet is for MONO-CHANNEL
.请注意,以下代码段适用于
MONO-CHANNEL
。
import pyaudio
import numpy
RATE=16000
RECORD_SECONDS = 2.5
CHUNKSIZE = 1024
# initialize portaudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNKSIZE)
frames = [] # A python-list of chunks(numpy.ndarray)
for _ in range(0, int(RATE / CHUNKSIZE * RECORD_SECONDS)):
data = stream.read(CHUNKSIZE)
frames.append(numpy.fromstring(data, dtype=numpy.int16))
#Convert the list of numpy-arrays into a 1D array (column-wise)
numpydata = numpy.hstack(frames)
# close stream
stream.stop_stream()
stream.close()
p.terminate()
This is a tested code.这是经过测试的代码。 It should work as charm.
它应该有魅力。 In order to check if your recorded data is correctly available in
numpydata
, you can add this following snippet after the previous code.为了检查您记录的数据是否在
numpydata
正确可用,您可以在之前的代码之后添加以下代码段。
import scipy.io.wavfile as wav
wav.write('out.wav',RATE,numpydata)
These lines will write your numpydata
into "out.wav".这些行会将您的
numpydata
写入“out.wav”。 Play the file to check the data.播放文件以检查数据。
PS: This is my first response in StackOverflow. PS:这是我在 StackOverflow 中的第一个回复。 Hope it helps.
希望能帮助到你。
import librosa
file = 'audio/a1.wav'
signal, _ = librosa.load(file)
print(type(signal))
This answer is similar to the first answer here, but I have included missing part of plotting the Audio Data.这个答案类似于这里的第一个答案,但我已经包含了绘制音频数据的缺失部分。
import pyaudio
import wave
import numpy as np
import noisereduce as nr
#This library helps us in plotting the audio
import matplotlib.pyplot as plt
def plotAudio2(output):
fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(20,4))
plt.plot(output, color='blue')
ax.set_xlim((0, len(output)))
plt.show()
CHUNK = 22050
FORMAT = pyaudio.paFloat32
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 20
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
data_sample = np.frombuffer(data, dtype=np.float32)
print("data sample")
plotAudio2(data_sample)
stream.stop_stream()
stream.close()
p.terminate()
I have tested above code snippet, this worked for me perfectly fine.我已经测试了上面的代码片段,这对我来说非常好。
Note: This code snippet was tested in Windows, and matplotlib might have some issue in MacOS (I am not sure though)注意:此代码片段在 Windows 中进行了测试, matplotlib在 MacOS 中可能存在一些问题(不过我不确定)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.