Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

In python, I'm going to create a spectrogram from a .wav file

Like this image, I want the final saved image similar to this

I just need a spectrogram that has many colors. I also tried tinker with this code, to give a try and add the colors, but after spending too much time, I couldn't able to figure it out. 

When I tried this tutorial

In this code, on the 17th line, the code got crashed, when I tried to run the code with the error

TypeError: 'numpy.float64' object cannot be interpreted as an integer.

Line 17:

samples = np.append(np.zeros(np.floor(frameSize/2.0)), sig)

I also tried fixing it by casting

samples = int(np.append(np.zeros(np.floor(frameSize/2.0)), sig))

Tried in this way too,

samples = np.append(np.zeros(int(np.floor(frameSize/2.0)), sig))

None of these worked. I just need to know how to convert my .wav file to spectrograms with many colors, so that it would be helpful for me to analyze them.

1 Answer

0 votes
by (26.4k points)

Try scipy.signal.spectrogram

import matplotlib.pyplot as plt

from scipy import signal

from scipy.io import wavfile

sample_rate, samples = wavfile.read('path-to-mono-audio-file.wav')

frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)

plt.pcolormesh(times, frequencies, spectrogram)

plt.imshow(spectrogram)

plt.ylabel('Frequency [Hz]')

plt.xlabel('Time [sec]')

plt.show()

Make sure, that your .wav file should be mono (single channel), not a stereo (dual channel).

I recommend you to read this scipy documentation. Just click on this link for documentation

Want to learn more about Python, Come & join: Python course

Do check out our tutorial video to learn more about python:

Browse Categories

...