import struct
import numpy as np
import matplotlib.pyplot as plt
CHUNK = 1024 * 4
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK
)
fig, ax = plt.subplots()
x = np.arange(0, 2 * CHUNK, 2)
line, = ax.plot(x, np.random.rand(CHUNK))
ax.set_ylim(0, 255)
ax.set_xlim(0, CHUNK)
while True:
data = stream.read(CHUNK)
data_int = np.array(struct.unpack(str(2 * CHUNK) + 'B', data), dtype='b')[::2] + 127
line.set_ydata(data_int)
fig.canvas.draw()
fig.canvas.flush_events()
试试这样写:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pyaudio
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK
)
fig, ax = plt.subplots()
x = np.arange(CHUNK)
line, = ax.plot(x, np.random.rand(CHUNK), lw=1, animated=True)
ax.set_ylim(0, 255)
ax.set_xlim(0, CHUNK)
def update_data(i):
data = stream.read(CHUNK)
data = np.frombuffer(data, dtype=np.int16)
plt.setp(line, 'ydata', data[:CHUNK])
return [line]
ani = FuncAnimation(fig, update_data, blit=True, interval=25, frames=1000)
plt.show()