Skip to content

Instantly share code, notes, and snippets.

@davecampbell
Last active May 30, 2019 17:04
Show Gist options
  • Save davecampbell/55068cb72e83bfbc8b556dd524f73624 to your computer and use it in GitHub Desktop.
Save davecampbell/55068cb72e83bfbc8b556dd524f73624 to your computer and use it in GitHub Desktop.
visualize audio signal from microphone
import sys
import pyaudio
import struct
import numpy as np
import matplotlib.pyplot as plt
%matplotlib tk
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=False,
frames_per_buffer=CHUNK
)
fig, ax = plt.subplots()
# x values go from 0 to size of CHUNK
x = np.arange(0, CHUNK)
# make a plotted line that is x long and random y values, CHUNK in length
line, = ax.plot(x, np.random.randn(CHUNK))
# set the plot limits
# x goes from 0 to CHUNK
ax.set_xlim(0, CHUNK)
# range of a 'signed int16' is this
ax.set_ylim(-32768, 32767)
# so forever...
while True:
# get the data from the audio source and store it as an int16
amplitude = np.fromstring(stream.read(CHUNK), dtype='int16')
# set the y values of line
line.set_ydata(amplitude)
# and draw it
fig.canvas.draw()
fig.canvas.flush_events()
# example of my output:
# <img src = "http://i.imgur.com/UDO5NAX.jpg">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment