Python:从歌曲中获取频率

时间:2019-11-30 10:44:28

标签: python frequency

我正在编写一个代码,用于用4个灯泡进行灯光表演,他们将根据歌曲切换它们的组合。因此,我必须听一首歌的频率。我找到了这段代码,基本上就是我想要的。

# Read in a WAV and find the freq's
import pyaudio
import wave
import numpy as np

chunk = 2024

# open up a wave
wf = wave.open('Audio_3.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# use a Blackman window
window = np.blackman(chunk)
# open stream
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
print(len(data))
print(chunk*swidth)
while len(data) == chunk*swidth:
    # write data out to the audio stream
    stream.write(data)
    # unpack the data and times by the hamming window
    indata = np.array(wave.struct.unpack("%dh"%(len(data)/swidth),\
                                         data))*window
    # Take the fft and square each value
    fftData=abs(np.fft.rfft(indata))**2
    # find the maximum
    which = fftData[1:].argmax() + 1
    # use quadratic interpolation around the max
    if which != len(fftData)-1:
        y0,y1,y2 = np.log(fftData[which-1:which+2:])
        x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
        # find the frequency and output it
        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()

但是,问题在于此代码仅适用于基本声音。当我尝试将这段代码用作歌曲时,循环变为假。是否有用于从歌曲中获取频率的代码?还是其他方式?

1 个答案:

答案 0 :(得分:0)

我认为立体声文件引起了麻烦,因为数据大小最终将是样本宽度* num_samples * num_channels。下列方法似乎可以正常工作,因为由audacity产生的440Hz音频给出了恒定的433 + -1Hz(错误来自fft或audacity的生成器)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="false" />
        <rewrite>
            <rules>
                <clear />
                <rule name="UrlWithPimRewrite" stopProcessing="true">
                    <match url="pim.*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <serverVariables>
                        <set name="HTTP_X_ORIGINAL_ACCEPT_ENCODING" value="{HTTP_ACCEPT_ENCODING}" />
                        <set name="HTTP_ACCEPT_ENCODING" value="" />
                    </serverVariables>
                    <action type="Rewrite" url="{C:1}://localhost:1512/{R0}" appendQueryString="true" logRewrittenUrl="false" />
                </rule>
                <rule name="UrlWithoutPIM" enabled="true" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{URL}" pattern="/pim" negate="true" />
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <serverVariables>
                        <set name="HTTP_X_ORIGINAL_ACCEPT_ENCODING" value="{HTTP_ACCEPT_ENCODING}" />
                        <set name="HTTP_ACCEPT_ENCODING" value="" />
                    </serverVariables>
                    <action type="Rewrite" url="{C:1}://localhost:1512/pim/webaccess" appendQueryString="false" logRewrittenUrl="false" />
                </rule>
            </rules>
            <outboundRules>
                <clear />
                <rule name="RestoreAcceptEncoding" preCondition="NeedsRestoringAcceptEncoding">
                    <match serverVariable="HTTP_ACCEPT_ENCODING" pattern="^(.*)" />
                    <action type="Rewrite" value="{HTTP_X_ORIGINAL_ACCEPT_ENCODING}" />
                </rule>
                <preConditions>
                    <preCondition name="NeedsRestoringAcceptEncoding">
                        <add input="{HTTP_X_ORIGINAL_ACCEPT_ENCODING}" pattern=".+" />
                    </preCondition>
                </preConditions>
            </outboundRules>
        </rewrite>
        <urlCompression doStaticCompression="true" />
        <directoryBrowse enabled="false" />
    </system.webServer>
</configuration>