如何使用python matplotlib库从wav文件中提取数据?

时间:2016-01-12 11:16:58

标签: python audio matplotlib fft wav

我正在尝试从wav文件中提取数据,用于每个频率的音频分析及其相对于时间的幅度,我的目的是为大学项目的机器学习算法运行此数据,经过一些谷歌搜索后我发现这可以通过Python的matplotlib库来完成,我看到了一些运行短傅立叶变换的示例代码并绘制了这些wav文件的频谱图,但是无法理解如何使用该库来提取数据(所有频率的幅度)在音频文件中的给定时间)并将其存储在3D数组或.mat文件中。 这是我在一些website上看到的代码:

#!/usr/bin/env python

""" This work is licensed under a Creative Commons Attribution 3.0 Unported License.
Frank Zalkow, 2012-2013 """

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(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=(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[:,scale[i]:], axis=1)
        else:        
            newspec[:,i] = np.sum(spec[:,scale[i]: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[scale[i]:])]
        else:
            freqs += [np.mean(allfreqs[scale[i]: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)

    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()
plotstft("abc.wav")

请指导我了解如何提取数据,如果没有通过matplotlib,请推荐一些其他库来帮助我实现这一目标。

2 个答案:

答案 0 :(得分:1)

首先,这看起来像我的代码,据说是CC许可证。我不太认真,但你不应该忽视这些方面(在这种情况下你省略了作者身份声明),其他人可能会对这种事情更加愤怒。

对于你的问题:在这段代码中,stft不是由matplotlib计算的,而是由numpy计算的。你可以这样得到它:

samplerate, samples = wav.read(audiopath)
s = stft(samples, 1024)

我不确定你为什么要3D阵列?它是一个二维数组,但它很复杂。如果要将其保存在.mat文件中:

from scipy.io import savemat
savemat("file.mat", {'arr': s})

答案 1 :(得分:0)

一旦将wav音频文件读入变量样本,就可以看到它被传递给一个名为stft的函数:

.CoverPhoto {
  width: 400px;
  position: relative;
}
.CoverPhoto:hover:after {
  opacity: 1;
}
.CoverPhoto:hover .content {
  transform: translateX(0);
  opacity: 1;
}
.CoverPhoto:after {
  transition: all 0.3s ease-in;
  content: "";
  position: absolute;
  top: 0;
  padding: 0;
  z-index: 2;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  background: rgba(0, 0, 0, 0.7);
}
.CoverPhoto img {
  width: 100%;
}

.content {
  transition: all 0.3s ease-in;
  transform: translateX(-100%);
  z-index: 10;
  color: #fff;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

这里你已经可以以整数的形式访问var样本中的音频样本...请注意,位深会影响每个样本的字节数,表示为一系列整数...也知道你的字节顺序(从左到右或反之亦然)...但是在函数stft中,数组在传递到函数np.fft.rfft

之前被进一步处理为变量:frames中的浮点数组

根据您的需要,这些是您的访问选择,而无需进行任何自己的处理