PYTHON 声音文件 频谱分析 FFT

import os
import time
import wave
import numpy as np
import numpy.core._dtype_ctypes
import multiprocessing
import matplotlib.pylab as pl

def fft_show(wavdata, Fr, figure_num, cmap0):
    N = Fr
    df = 1
    freq =[df*n for n in range(0, N)]
    c = np.fft.fft(wavdata[:N])
    print('len: {0}:{1}{2}{3}'.format(len(c), c[0], c[1], c[2]))

    d = int(len(c)/2)
    for index in range(d):
        print("freq:{0}, value:{1}".format(freq[index], abs(c[index])))

    fig, ax = pl.plt.subplots(1, 1)
    ax.plot(freq[:d-1], abs(c[:d-1]), color='red')
    ax.set_xlabel('Freq(HZ)')
    ax.set_ylabel('Y(freq)')
    pl.plt.show()

def creat_figure(waveData, Fs, figure_num, cmap0):
    pl.plt.figure(figsize=(8, 4.0))
    print('Child process {0} {1} Running {2} '.format(figure_num, os.getpid(), time.time()))
    pl.specgram(waveData, NFFT=512, Fs=Fs, noverlap=256, pad_to=8192, mode='magnitude', scale='dB' \
                  , vmin=0, cmap=cmap0)
    print('Child process {0} {1} specgram {2} '.format(figure_num, os.getpid(), time.time()))
    #pl.plt.savefig('fft\\mono_%d.png'%(figure_num+1))
    #pl.plt.savefig('fft\\mono_%d.png'% (figure_num+1), dpi=100)
    pl.plt.savefig('fft\\mono_%d.png'% (figure_num+1), bbox_inches='tight')
    pl.plt.cla()
    print('Child process {0} {1} end {2} '.format(figure_num, os.getpid(), time.time()))

if __name__ == '__main__':
    multiprocessing.freeze_support()
    time0 = time.time()
    wavefile = wave.open("d:\\1k.wav", 'rb')
    params = wavefile.getparams()
    nchannels, sample_width, framerate, numframe = params[:4]
    print("framerate:", framerate)
    print("sample_width:", sample_width)
    print("nchannels:", nchannels)
    print("numframe:", numframe)
    strData = wavefile.readframes(numframe)
    waveData = np.frombuffer(strData, dtype=np.int16)
    waveData = np.reshape(waveData, [numframe, nchannels])
    wavefile.close()
    # pl.plt.figure(figsize=(6.4, 4.0))
    cmap_fft = pl.plt.get_cmap('plasma')
    fft_show(waveData[:, 0], framerate, 0, cmap_fft)


    #p = multiprocessing.Pool(processes=4)
    #for num in range(nchannels):
        #p.apply_async(creat_figure, args=(waveData[:,num], numframe, num, cmap_fft))
        #p.apply_async(fft_show, args=(waveData[:, num], framerate, num, cmap_fft))
    #p.close()
    #p.join()
    print('Running time: %s Seconds' % (time.time() - time0))
 

你可能感兴趣的:(python)