How to separate frequency of audiofile

孤街浪徒 提交于 2019-12-11 10:15:16

问题


I simply want to determine frequencies of a .mp3 or .wav file and print it

import pyaudio
import wave
import numpy as np

chunk = 2048
wf = wave.open('/home/pi/Adhuri.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
window = np.blackman(chunk)
p = pyaudio.PyAudio()
stream = p.open(format =
            p.get_format_from_width(wf.getsampwidth()),
            channels = wf.getnchannels(),
            rate = RATE,
            output = True)

# read some data
data = wf.readframes(chunk)
# play stream and find the frequency of each chunk
while len(data) == chunk*swidth:
    print "ok"
    stream.write(data)
    indata = np.array(wave.struct.unpack("%dh"%(len(data)/swidth),\
                                     data))*window
    fftData=abs(np.fft.rfft(indata))**2
    which = fftData[1:].argmax() + 1
    if which != len(fftData)-1:
        y0,y1,y2 = np.log(fftData[which-1:which+2:])
        x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
        thefreq = (which+x1)*RATE/chunk
        print "The freq is %f Hz." % (thefreq)
    else:
        thefreq = which*RATE/chunk
        print "The freq is %f Hz." % (thefreq)
    # read some more data
    data = wf.readframes(chunk)
if data:
    stream.write(data)
stream.close()
p.terminate()

It does not satisfy while len(data) == chunkswidth: and when i am writing while len(data) != chunkswidth: only then it enters into loop and shows an error message valueerror: operands could not together broadcast with shapes (4096)(2048) . how to solve this problem?

来源:https://stackoverflow.com/questions/30637384/how-to-separate-frequency-of-audiofile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!