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))
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值