Using Librosa to plot a mel-spectrogram

23.7k views Asked by At

I am having trouble creating a mel-spectrogram in librosa using a custom file path to my sound.

I am following this documentation: https://librosa.github.io/librosa/generated/librosa.feature.melspectrogram.html

And I have looked at this stack overflow post: Spectrograms generated using Librosa don't look consistent with Kaldi?

However none of this helped me solve my issue.

import librosa
y, sr = librosa.load("path_to_my_wav_file")
librosa.feature.melspectrogram(y=y, sr=sr)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.power_to_db(y,                                              
ref=np.max), y_axis='mel', fmax=8000, x_axis='time')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel spectrogram')
plt.tight_layout()

Can someone tell me how to fix this code so that it properly displays and saves the mel-spectrogram to jpg file? Thanks!

1

There are 1 answers

7
zxf On BEST ANSWER

oh, Your question is mainly about how to save it as jpg? If you just want to display pictures,You just need to add a line of code: plt.show()

if you want save a jpg, no axis, no white edge:

import os
import matplotlib
matplotlib.use('Agg') # No pictures displayed 
import pylab
import librosa
import librosa.display
import numpy as np

sig, fs = librosa.load('path_to_my_wav_file')   
# make pictures name 
save_path = 'test.jpg'

pylab.axis('off') # no axis
pylab.axes([0., 0., 1., 1.], frameon=False, xticks=[], yticks=[]) # Remove the white edge
S = librosa.feature.melspectrogram(y=sig, sr=fs)
librosa.display.specshow(librosa.power_to_db(S, ref=np.max))
pylab.savefig(save_path, bbox_inches=None, pad_inches=0)
pylab.close()