如何在1秒间隔内对wav文件进行频率分析?(非图形化)

时间:2016-12-04 08:37:34

标签: python fft wav frequency analysis

我制作钢琴游戏机,我需要wav频率的原始值。我发现了一些我想要的相似代码。我想将此代码修改为1秒间隔分析并存储在数组上。你能救我吗?

import wave 
import struct
import numpy as np
import wave
import contextlib
import RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BCM)


GPIO.setup(6, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(21, GPIO.IN)


if __name__ == '__main__':
    fname = "test.wav"
    frate = 0
    data_size = 0

    with contextlib.closing(wave.open(fname,'r')) as f:
        frate = f.getframerate()
        data_size = f.getnframes()

    wav_file = wave.open(fname, 'r')
    data = wav_file.readframes(data_size)
    data_size = data_size * wav_file.getnchannels()

    print wav_file.getparams()

    wav_file.close()
    data = struct.unpack('{n}h'.format(n=data_size), data)
    data = np.array(data)

    w = np.fft.fft(data)
    freqs = np.fft.fftfreq(len(w))
    print(freqs.min(), freqs.max())

    # Find the peak in the coefficients

    idx = np.argmax(np.abs(w))
    freq = freqs[idx]
    freq_in_hertz = abs(freq * frate)

    print(freq_in_hertz)


#1 옥타브 대역 주파수 
if 16 <=freq_in_hertz and freq_in_hertz<=17 :
    GPIO.output(6, HIGH)
    time.sleep(1)

    if GPIO.input(21) :
        GPIO.output(17, HIGH)
        GPIO.output(27, LOW)

    else :
        GPIO.output(17, LOW)
        GPIO.output(27, HIGH)

elif 18<=freq_in_hertz and freq_in_hertz<=20 :
    GPIO.output(6, HIGH)
    time.sleep(1)

    if GPIO.input(21) :
        GPIO.output(17, HIGH)
        GPIO.output(27, LOW)

    else :
        GPIO.output(17, LOW)
        GPIO.output(27, HIGH)

0 个答案:

没有答案