Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot spectogram from mp3

I am trying to plot a spectogram straight from an mp3 file in python 2.7.3 (using ubuntu). I can do it from a wav file as follows.

#!/usr/bin/python
from scikits.audiolab import wavread
from pylab import *

signal, fs, enc = wavread('XC124158.wav')
specgram(signal)
show()

What's the cleanest way to do the same thing from an mp3 file instead of a wav? I don't want to convert all the mp3 files to wav if I can avoid it.

like image 768
Majid Avatar asked Mar 09 '13 14:03

Majid


People also ask

How do you save a spectrogram as an image?

Convert the power spectrogram (amplitude squared) to decibel (dB) units, using power_to_db() method.. Display the spectrogram as img (we can save it here). Save the img using savefig(). Display the image using plt.


1 Answers

Another very simple way of plotting spectrogram of mp3 file.

from pydub import AudioSegment
import matplotlib.pyplot as plt
from scipy.io import wavfile
from tempfile import mktemp

mp3_audio = AudioSegment.from_file('speech.mp3', format="mp3")  # read mp3
wname = mktemp('.wav')  # use temporary file
mp3_audio.export(wname, format="wav")  # convert to wav
FS, data = wavfile.read(wname)  # read wav file
plt.specgram(data, Fs=FS, NFFT=128, noverlap=0)  # plot
plt.show()

This uses the pydub library which is more convenient compared to calling external commands. This way you can iterate over all your .mp3 files without having to convert them to .wav prior to plotting.

enter image description here

like image 86
dsalaj Avatar answered Oct 25 '22 12:10

dsalaj