How to convert a .wav file to a spectrogram in python3

前端 未结 4 1785
-上瘾入骨i
-上瘾入骨i 2020-11-29 03:18

I am trying to create a spectrogram from a .wav file in python3.

I want the final saved image to look similar to this image:

I have tried the foll

4条回答
  •  感情败类
    2020-11-29 03:26

    You can use librosa for your mp3 spectogram needs. Here is some code I found, thanks to Parul Pandey from medium. The code I used is this,

    # Method described here https://stackoverflow.com/questions/15311853/plot-spectogram-from-mp3
    
    from pydub import AudioSegment
    import matplotlib.pyplot as plt
    from scipy.io import wavfile
    from tempfile import mktemp
    
    def plot_mp3_matplot(filename):
        """
        plot_mp3_matplot -- using matplotlib to simply plot time vs amplitude waveplot
        
        Arguments:
        filename -- filepath to the file that you want to see the waveplot for
        
        Returns -- None
        """
        
        # sr is for 'sampling rate'
        # Feel free to adjust it
        x, sr = librosa.load(filename, sr=44100)
        plt.figure(figsize=(14, 5))
        librosa.display.waveplot(x, sr=sr)
    
    def convert_audio_to_spectogram(filename):
        """
        convert_audio_to_spectogram -- using librosa to simply plot a spectogram
        
        Arguments:
        filename -- filepath to the file that you want to see the waveplot for
        
        Returns -- None
        """
        
        # sr == sampling rate 
        x, sr = librosa.load(filename, sr=44100)
        
        # stft is short time fourier transform
        X = librosa.stft(x)
        
        # convert the slices to amplitude
        Xdb = librosa.amplitude_to_db(abs(X))
        
        # ... and plot, magic!
        plt.figure(figsize=(14, 5))
        librosa.display.specshow(Xdb, sr = sr, x_axis = 'time', y_axis = 'hz')
        plt.colorbar()
        
    # same as above, just changed the y_axis from hz to log in the display func    
    def convert_audio_to_spectogram_log(filename):
        x, sr = librosa.load(filename, sr=44100)
        X = librosa.stft(x)
        Xdb = librosa.amplitude_to_db(abs(X))
        plt.figure(figsize=(14, 5))
        librosa.display.specshow(Xdb, sr = sr, x_axis = 'time', y_axis = 'log')
        plt.colorbar()    
    

    Cheers!

提交回复
热议问题