Skip to content

Instantly share code, notes, and snippets.

@AhmadMoussa
Last active December 9, 2019 07:33
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 AhmadMoussa/eb99a76706ccb23a3cda44b47df91441 to your computer and use it in GitHub Desktop.
Save AhmadMoussa/eb99a76706ccb23a3cda44b47df91441 to your computer and use it in GitHub Desktop.
Interactive Matplotlib tool that allows you to plot a waveform as well as zoom in on certain spots
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import librosa
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.35)
samples = 1
audio, sr = librosa.core.load("Snare.wav") # load your audio here
begin, begin_init = 0, 0
end = len(audio)
end_init = end
t = np.arange(0, int(len(audio)), 1)
l, = plt.plot(audio[begin:end], lw=1)
ax.margins(x=0)
axcolor = 'lightgoldenrodyellow'
axmini = plt.axes([0.1, 0.1, 0.8, 0.1], facecolor=axcolor)
axmini.plot(audio[begin:end], lw=0.3)
axmini.margins(x=0)
axend = plt.axes([0.1, 0.22, 0.8, 0.03], facecolor=axcolor)
axbegin = plt.axes([0.1, 0.27, 0.8, 0.03], facecolor=axcolor)
sbegin = Slider(axbegin, 'Begin', 0, int(len(audio)), valinit=begin_init, valstep=samples)
send = Slider(axend, 'End', 0, int(len(audio)), valinit=end_init, valstep=samples)
def update(val):
end = send.val
begin = sbegin.val
ax.cla()
axmini.cla()
ax.plot(audio[int(begin):int(end)], lw=1)
axmini.plot(audio, lw=0.5)
axmini.axvspan(0, begin, alpha=0.5, color='red')
axmini.axvspan(end, len(audio), alpha=0.5, color='red')
ax.margins(x=0)
axmini.margins(x=0)
sbegin.on_changed(update)
send.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
sbegin.reset()
send.reset()
button.on_clicked(reset)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment