Skip to content

Instantly share code, notes, and snippets.

@PaperStrike
Last active February 27, 2021 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaperStrike/5f5b75edf7f175064699d3c35208c751 to your computer and use it in GitHub Desktop.
Save PaperStrike/5f5b75edf7f175064699d3c35208c751 to your computer and use it in GitHub Desktop.
Plot mic input of headset
#!/usr/bin/env python3
"""Plot the live microphone signal(s) with matplotlib.
Matplotlib and NumPy have to be installed.
Edited from:
https://github.com/spatialaudio/python-sounddevice/blob/0.4.1/examples/plot_input.py
"""
import argparse
import queue
import sys
from matplotlib.animation import FuncAnimation
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plt
import numpy as np
import sounddevice as sd
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
args, remaining = parser.parse_known_args()
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[parser])
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
parser.add_argument(
'-w', '--duration', type=float, default=4000, metavar='DURATION',
help='visible time slot (default: %(default)s ms)')
parser.add_argument(
'-a', '--amplitude', type=float, default=1.,
help='maximum value visible (default: %(default)s)')
parser.add_argument(
'-i', '--interval', type=float, default=50,
help='minimum time between plot updates (default: %(default)s ms)')
parser.add_argument(
'-b', '--blocksize', type=int, default=10, help='block size (in samples)')
parser.add_argument(
'-r', '--samplerate', type=int, default=1000,
help='sampling rate of audio device')
args = parser.parse_args(remaining)
q = queue.Queue()
def audio_callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(indata[::, [0, 1]])
def update_plot(frame):
"""This is called by matplotlib for each plot update.
Typically, audio callbacks happen more frequently than plot updates,
therefore the queue tends to contain multiple blocks of audio data.
"""
global plot_data
while True:
try:
data = q.get_nowait()
except queue.Empty:
break
shift = len(data)
plot_data = np.roll(plot_data, -shift, axis=0)
diff = [x[1] - x[0] for x in data]
plot_data[-shift:, :] = [[diff[i], data[i][0]] for i in
range(args.blocksize)]
for column, line in enumerate(lines):
line.set_ydata(plot_data[:, column])
return lines
try:
length = int(args.duration * args.samplerate / 1000)
plot_data = np.zeros((length, 2))
fig, ax = plt.subplots()
lines = ax.plot(plot_data)
ax.legend(['Diff', 'Channel 1'], loc='lower left', ncol=2)
# X
ax.xaxis.set_major_locator(MultipleLocator(args.duration / 20))
# Y
ax.axis((0, len(plot_data), - args.amplitude, args.amplitude))
ax.set_yticks([0])
ax.yaxis.grid(True)
ax.yaxis.set_major_locator(MultipleLocator(args.amplitude / 20))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', length / 2))
fig.tight_layout()
ani = FuncAnimation(fig, update_plot, interval=args.interval, blit=True)
with sd.InputStream(
device=args.device, channels=2,
samplerate=args.samplerate, blocksize=args.blocksize,
callback=audio_callback):
plt.show()
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment