Python 中的音频频率 [英] Audio Frequencies in Python

查看:20
本文介绍了Python 中的音频频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码来分析一个声音所唱的单个音频频率.我需要一种方法来分析音符的频率.目前我正在使用 PyAudio 录制音频文件,该文件存储为 .wav,然后立即播放.

将 numpy 导入为 np导入pyaudio进口波# 打开一波wf = wave.open('file.wav', 'rb')swidth = wf.getsampwidth()速率 = wf.getframerate()# 使用布莱克曼窗窗口 = np.blackman(chunk)# 打开流p = pyaudio.PyAudio()流 = p.open(格式 =p.get_format_from_width(wf.getsampwidth()),频道 = wf.getnchannels(),费率 = 费率,输出 = 真)# 读取一些数据数据 = wf.readframes(chunk)打印(len(数据))打印(块*宽)# 播放流并找到每个块的频率而 len(data) == chunk*swidth:# 将数据写入音频流流.写(数据)# 通过汉明窗解包数据和时间indata = np.array(wave.struct.unpack("%dh"%(len(data)/swidth),数据))*窗口# 取 fft 并平方每个值fftData=abs(np.fft.rfft(indata))**2# 找到最大值which = fftData[1:].argmax() + 1# 在最大值周围使用二次插值如果哪个 != 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/chunkprint("频率为 %f Hz." % (thefreq))别的:thefreq = which*RATE/chunkprint("频率为 %f Hz." % (thefreq))# 读取更多数据数据 = wf.readframes(chunk)如果数据:流.写(数据)流关闭()p.terminate()

问题出在while循环上.由于某种原因,条件永远不会成立.我打印了两个值(len(data) 和 (chunk*swidth)),它们分别是 8192 和 4096.然后我尝试在 while 循环中使用 2*chunk*swidth,这引发了这个错误:

文件C:UsersOllieDocumentsComputing A Level CApyaudio test.py",第102行,在<module>数据))*窗口ValueError:操作数无法与形状一起广播 (4096,) (2048,)

解决方案

下面的这个函数查找频谱.我还包含了一个正弦信号和一个 WAV 文件示例应用程序.这是出于教育目的;您也可以使用现成的


您还可以参考

I'm writing a code to analyse a single audio frequency sung by a voice. I need a way to analyse the frequency of the note. Currently I am using PyAudio to record the audio file, which is stored as a .wav, and then immediately play it back.

import numpy as np
import pyaudio
import wave

# open up a wave
wf = wave.open('file.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)

print(len(data))
print(chunk*swidth)

# play stream and find the frequency of each chunk
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()

The problem is with the while loop. The condition is never true for some reason. I printed out the two values (len(data) and (chunk*swidth)), and they were 8192 and 4096 respectively. I then tried using 2*chunk*swidth in the while loop, which threw this error:

File "C:UsersOllieDocumentsComputing A Level CApyaudio test.py", line 102, in <module>
data))*window
ValueError: operands could not be broadcast together with shapes (4096,) (2048,)

解决方案

This function below finds the frequency spectrum. I have also included a sine signal and a WAV file sample application. This is for educational purposes; you may alternatively use the readily available matplotlib.pyplot.magnitude_spectrum (see below).

from scipy import fft, arange
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
import os


def frequency_spectrum(x, sf):
    """
    Derive frequency spectrum of a signal from time domain
    :param x: signal in the time domain
    :param sf: sampling frequency
    :returns frequencies and their content distribution
    """
    x = x - np.average(x)  # zero-centering

    n = len(x)
    k = arange(n)
    tarr = n / float(sf)
    frqarr = k / float(tarr)  # two sides frequency range

    frqarr = frqarr[range(n // 2)]  # one side frequency range

    x = fft(x) / n  # fft computing and normalization
    x = x[range(n // 2)]

    return frqarr, abs(x)


# Sine sample with a frequency of 1hz and add some noise
sr = 32  # sampling rate
y = np.linspace(0, 2*np.pi, sr)
y = np.tile(np.sin(y), 5)
y += np.random.normal(0, 1, y.shape)
t = np.arange(len(y)) / float(sr)

plt.subplot(2, 1, 1)
plt.plot(t, y)
plt.xlabel('t')
plt.ylabel('y')

frq, X = frequency_spectrum(y, sr)

plt.subplot(2, 1, 2)
plt.plot(frq, X, 'b')
plt.xlabel('Freq (Hz)')
plt.ylabel('|X(freq)|')
plt.tight_layout()


# wav sample from https://freewavesamples.com/files/Alesis-Sanctuary-QCard-Crickets.wav
here_path = os.path.dirname(os.path.realpath(__file__))
wav_file_name = 'Alesis-Sanctuary-QCard-Crickets.wav'
wave_file_path = os.path.join(here_path, wav_file_name)
sr, signal = wavfile.read(wave_file_path)

y = signal[:, 0]  # use the first channel (or take their average, alternatively)
t = np.arange(len(y)) / float(sr)

plt.figure()
plt.subplot(2, 1, 1)
plt.plot(t, y)
plt.xlabel('t')
plt.ylabel('y')

frq, X = frequency_spectrum(y, sr)

plt.subplot(2, 1, 2)
plt.plot(frq, X, 'b')
plt.xlabel('Freq (Hz)')
plt.ylabel('|X(freq)|')
plt.tight_layout()

plt.show()


You may also refer to SciPy's Fourier Transforms and Matplotlib's magnitude spectrum plotting pages for extra reading and features.

magspec = plt.magnitude_spectrum(y, sr)  # returns a tuple with the frequencies and associated magnitudes

这篇关于Python 中的音频频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆