Skip to content

Instantly share code, notes, and snippets.

@JanWilczek
Created February 24, 2024 16:57
Show Gist options
  • Select an option

  • Save JanWilczek/8ad9f37b2a10a77785947374487047a0 to your computer and use it in GitHub Desktop.

Select an option

Save JanWilczek/8ad9f37b2a10a77785947374487047a0 to your computer and use it in GitHub Desktop.
Easily display audio samples with a stem plot and (optionally) save to a file. Uses matplotlib for plotting and saving the figure, pathlib for path handling, and numpy for sine generation. I use this snippet all the time. Feel free to treat it as a template: copy, paste & tweak as you need!
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
IMG_OUTPUT_PATH = Path('img')
def save(output_path: Path):
output_path.parent.mkdir(parents=True, exist_ok=True)
SAVE_PARAMS = {'dpi': 300, 'bbox_inches': 'tight', 'transparent': True}
plt.savefig(output_path, **SAVE_PARAMS)
def stem_signal(signal):
plt.rcParams.update({'font.size': 20})
COLOR = '#ef7600'
plt.figure(figsize=(12,6))
sample_count = signal.shape[0]
xlim = [-0.5, sample_count - 0.5]
plt.hlines(0, xlim[0], xlim[1], colors='k')
markerline, stemlines, baseline = plt.stem(signal)
plt.setp(markerline, color=COLOR, markersize=10)
plt.setp(stemlines, color=COLOR, linewidth=3)
plt.setp(baseline, visible=False)
plt.xlim(xlim)
plt.xlabel('samples $n$')
plt.ylabel('amplitude')
plt.yticks([-1, 0, 1])
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
def stem_signal_and_save(signal, output_path: Path):
stem_signal(signal)
# plt.show() # closes the figure
save(output_path)
plt.close()
def main():
sample_rate = 44100
length_seconds = 5
frequency = 880
sample_indices = np.arange(length_seconds * sample_rate)
signal = np.sin(2 * np.pi * frequency * sample_indices / sample_rate)
stem_signal_and_save(signal[:40], IMG_OUTPUT_PATH / 'sine_samples.png')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment