如何在python3中将.wav文件转换为频谱图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44787437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:28:17  来源:igfitidea点击:

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

pythonnumpyaudiomatplotlibspectrogram

提问by Sreehari R

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

我正在尝试从 python3 中的 .wav 文件创建频谱图。

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

我希望最终保存的图像看起来类似于此图像:

I have tried the following:

我尝试了以下方法:

This stack overflow post: Spectrogram of a wave file

此堆栈溢出帖子: 波形文件的频谱图

This post worked, somewhat. After running it, I got

这篇文章有点奏效。运行后,我得到了

However, This graph does not contain the colors that I need. I need a spectrogram that has colors. I tried to tinker with this code to try and add the colors however after spending significant time and effort on this, I couldn't figure it out!

但是,此图不包含我需要的颜色。我需要一个有颜色的光谱图。我尝试修改此代码以尝试添加颜色,但是在为此花费了大量时间和精力之后,我无法弄清楚!

I then tried thistutorial.

然后我尝试了这个教程。

This code crashed(on line 17) when I tried to run it with the error TypeError: 'numpy.float64' object cannot be interpreted as an integer.

当我尝试运行该代码时出现错误 TypeError: 'numpy.float64' object cannot be interpret as an integer 时,此代码崩溃(在第 17 行)。

line 17:

第 17 行:

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

I tried to fix it by casting

我试图通过铸造来修复它

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

and I also tried

我也试过

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

However neither of these worked in the end.

然而,这些最终都没有奏效。

I would really like to know how to convert my .wav files to spectrograms with color so that I can analyze them! Any help would be appreciated!!!!!

我真的很想知道如何将我的 .wav 文件转换为带有颜色的频谱图,以便我可以分析它们!任何帮助,将不胜感激!!!!!

Please tell me if you want me to provide any more information about my version of python, what I tried, or what I want to achieve.

如果您希望我提供有关我的 Python 版本、我尝试过的内容或我想要实现的内容的更多信息,请告诉我。

回答by Tom Wyllie

Use scipy.signal.spectrogram.

使用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()

Be sure that your wav file is mono (single channel) and not stereo (dual channel) before trying to do this. I highly recommend reading the scipy documentation at https://docs.scipy.org/doc/scipy- 0.19.0/reference/generated/scipy.signal.spectrogram.html.

在尝试执行此操作之前,请确保您的 wav 文件是单声道(单声道)而不是立体声(双声道)。我强烈建议阅读https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.signal.spectrogram.html 上的 scipy 文档。

Putting plt.pcolormeshbefore plt.imshowseems to fix some issues, as pointed out by @Davidjb, and if unpacking error occurs, follow the steps by @cgnorthcutt below.

正如@Davidjb 所指出的,放在plt.pcolormesh之前plt.imshow似乎解决了一些问题,如果发生解包错误,请按照下面@cgnorthcutt 的步骤操作。

回答by Mudit Verma

import os
import wave

import pylab
def graph_spectrogram(wav_file):
    sound_info, frame_rate = get_wav_info(wav_file)
    pylab.figure(num=None, figsize=(19, 12))
    pylab.subplot(111)
    pylab.title('spectrogram of %r' % wav_file)
    pylab.specgram(sound_info, Fs=frame_rate)
    pylab.savefig('spectrogram.png')
def get_wav_info(wav_file):
    wav = wave.open(wav_file, 'r')
    frames = wav.readframes(-1)
    sound_info = pylab.fromstring(frames, 'int16')
    frame_rate = wav.getframerate()
    wav.close()
    return sound_info, frame_rate

for A Capella Science - Bohemian Gravity!this gives:

对于卡佩拉科学 - 波西米亚重力!这给出:

enter image description here

在此处输入图片说明

Use graph_spectrogram(path_to_your_wav_file). I don't remember the blog from where I took this snippet. I will add the link whenever I see it again.

使用graph_spectrogram(path_to_your_wav_file). 我不记得我从哪里获取这个片段的博客。每当我再次看到它时,我都会添加链接。

回答by Beginner

I have fixed the errors you are facing for http://www.frank-zalkow.de/en/code-snippets/create-audio-spectrograms-with-python.html
This implementation is better because you can change the binsize(e.g. binsize=2**8)

我已经修复了您在http://www.frank-zalkow.de/en/code-snippets/create-audio-spectrograms-with-python.html 中遇到的错误
此实现更好,因为您可以更改binsize(例如binsize=2**8

import numpy as np
from matplotlib import pyplot as plt
import scipy.io.wavfile as wav
from numpy.lib import stride_tricks

""" short time fourier transform of audio signal """
def stft(sig, frameSize, overlapFac=0.5, window=np.hanning):
    win = window(frameSize)
    hopSize = int(frameSize - np.floor(overlapFac * frameSize))

    # zeros at beginning (thus center of 1st window should be for sample nr. 0)   
    samples = np.append(np.zeros(int(np.floor(frameSize/2.0))), sig)    
    # cols for windowing
    cols = np.ceil( (len(samples) - frameSize) / float(hopSize)) + 1
    # zeros at end (thus samples can be fully covered by frames)
    samples = np.append(samples, np.zeros(frameSize))

    frames = stride_tricks.as_strided(samples, shape=(int(cols), frameSize), strides=(samples.strides[0]*hopSize, samples.strides[0])).copy()
    frames *= win

    return np.fft.rfft(frames)    

""" scale frequency axis logarithmically """    
def logscale_spec(spec, sr=44100, factor=20.):
    timebins, freqbins = np.shape(spec)

    scale = np.linspace(0, 1, freqbins) ** factor
    scale *= (freqbins-1)/max(scale)
    scale = np.unique(np.round(scale))

    # create spectrogram with new freq bins
    newspec = np.complex128(np.zeros([timebins, len(scale)]))
    for i in range(0, len(scale)):        
        if i == len(scale)-1:
            newspec[:,i] = np.sum(spec[:,int(scale[i]):], axis=1)
        else:        
            newspec[:,i] = np.sum(spec[:,int(scale[i]):int(scale[i+1])], axis=1)

    # list center freq of bins
    allfreqs = np.abs(np.fft.fftfreq(freqbins*2, 1./sr)[:freqbins+1])
    freqs = []
    for i in range(0, len(scale)):
        if i == len(scale)-1:
            freqs += [np.mean(allfreqs[int(scale[i]):])]
        else:
            freqs += [np.mean(allfreqs[int(scale[i]):int(scale[i+1])])]

    return newspec, freqs

""" plot spectrogram"""
def plotstft(audiopath, binsize=2**10, plotpath=None, colormap="jet"):
    samplerate, samples = wav.read(audiopath)

    s = stft(samples, binsize)

    sshow, freq = logscale_spec(s, factor=1.0, sr=samplerate)

    ims = 20.*np.log10(np.abs(sshow)/10e-6) # amplitude to decibel

    timebins, freqbins = np.shape(ims)

    print("timebins: ", timebins)
    print("freqbins: ", freqbins)

    plt.figure(figsize=(15, 7.5))
    plt.imshow(np.transpose(ims), origin="lower", aspect="auto", cmap=colormap, interpolation="none")
    plt.colorbar()

    plt.xlabel("time (s)")
    plt.ylabel("frequency (hz)")
    plt.xlim([0, timebins-1])
    plt.ylim([0, freqbins])

    xlocs = np.float32(np.linspace(0, timebins-1, 5))
    plt.xticks(xlocs, ["%.02f" % l for l in ((xlocs*len(samples)/timebins)+(0.5*binsize))/samplerate])
    ylocs = np.int16(np.round(np.linspace(0, freqbins-1, 10)))
    plt.yticks(ylocs, ["%.02f" % freq[i] for i in ylocs])

    if plotpath:
        plt.savefig(plotpath, bbox_inches="tight")
    else:
        plt.show()

    plt.clf()

    return ims

ims = plotstft(filepath)