Search code examples
pythonpython-3.xmatplotlibpyaudio

Matplotlib not showing anything


I want to make a spectrum analyzer stream on macosx using this code. but not showing anything. matplotlib dosent open. can anyone help me what's wrong? python 3.8.0 matplotlib 3.1.1 PyAudio 0.2.11 numpy 1.17.3 scipy 1.3.1

import pyaudio
import struct
import numpy as np
import matplotlib.pyplot as plt

plt.ion()
plt.show()

CHUNK = 1024*4
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 10000

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(-256, 256)
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]-128
    line.set_ydata(data_int)
    fig.canvas.draw()
    fig.canvas.flush_events()

Solution

  • You must define a backend for matplotlib to use. Adding these two lines should do the job:

    import matplotlib
    matplotlib.use('MacOSX')