Skip to content

Instantly share code, notes, and snippets.

@nkpro2000sr
Last active February 21, 2020 07:01
Show Gist options
  • Save nkpro2000sr/beafc8b2bb2c7c265eaaf45963c2d59d to your computer and use it in GitHub Desktop.
Save nkpro2000sr/beafc8b2bb2c7c265eaaf45963c2d59d to your computer and use it in GitHub Desktop.
plot audio file in matplotlib
from matplotlib import pyplot as plt
import librosa
#For specgram
NFFT = 1024
noverlap = 900
#For MFCC
n_mfcc = 40
#Main
def plot(W, S, m, M, *p_An):
"""
$W : enable for Waveform
$S : enable for Specgram
$m : enable for MFCC
$M : enable for MFCC (specgram)
$p_An : path of audio files
"""
if not (W or S or m or M) : return None
shape = [len(p_An),sum((W, S, m, M))]
for i,path in enumerate(p_An):
s,sr = librosa.load(path,sr=16000)
mfcc = librosa.feature.mfcc(s,sr,n_mfcc=n_mfcc)
subindex = 1
if W :
subplt = plt.subplot(*shape,i*sum((W, S, m, M))+subindex)
subplt.plot(s)
subindex += 1
if S :
subplt = plt.subplot(*shape,i*sum((W, S, m, M))+subindex)
subplt.specgram(s, NFFT=NFFT, Fs=sr, noverlap=noverlap)
subindex += 1
if m :
subplt = plt.subplot(*shape,i*sum((W, S, m, M))+subindex)
subplt.plot(mfcc)
subindex += 1
if M :
subplt = plt.subplot(*shape,i*sum((W, S, m, M))+subindex)
subplt.specgram(mfcc, NFFT=NFFT, Fs=sr, noverlap=noverlap)
subindex += 1
return plt
@nkpro2000sr
Copy link
Author

nkpro2000sr commented Feb 9, 2020

eg:

plot(1,1,0,0,"music.mp3").show() #to show LineGraph and Spectrogram in window
plot(0,1,0,0,"music.mp3").savefig("Spectrogram.png") #to save the Spectrogram as image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment