当前位置: 首页 > 面试题库 >

Python中的音频频率

秦宏硕
2023-03-14
问题内容

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

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

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

File "C:\Users\Ollie\Documents\Computing A Level CA\pyaudio test.py", line 102, in <module>
data))*window
ValueError: operands could not be broadcast together with shapes (4096,) (2048,)

问题答案:

下面的此功能可查找频谱。我还提供了一个正弦信号和一个WAV文件示例应用程序。这是出于教育目的;您也可以使用易于使用的matplotlib.pyplot.magnitude_spectrum(请参见下文)。

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


def frequency_sepectrum(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)
    print(n)
    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_sepectrum(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_sepectrum(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()

您还可以参考SciPy的Fourier变换和Matplotlib的幅度谱绘图页面以获取更多信息和功能。

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


 类似资料:
  • 音频概述 没有音频的游戏是不完整的,例如背景音乐或音响效果。Unity 的音频系统灵活而强大。它可以导入大多数标准音频文件格式,并且为播放 3D 空间中的声音提供了复杂的功能,以及可选的音响效果,例如回音和过滤。Unity 还可以记录来自用户机器上任意可用麦克风的音频,以便在游戏过程中使用,或者用于存储和传输。 基础理论 在现实生活中,声音由对象发出,并被听众听到。声音被感知的方式取决于许多因素。

  • 主要内容:HTML 音频/视频 DOM 参考手册,HTML 音频/视频 方法,HTML 音频/视频属性,HTML 音频/视频事件HTML 音频/视频 DOM 参考手册 HTML5 DOM 为 <audio> 和 <video> 元素提供了方法、属性和事件。 这些方法、属性和事件允许您使用 JavaScript 来操作 <audio> 和 <video> 元素。 HTML 音频/视频 方法 方法 描述 addTextTrack() 向音频/视频添加新的文本轨道。 canPlayType() 检测浏

  • 音频 Unity 的音频功能包括完整 3D 空间声音、实时混音和母带处理、混音层次结构、快照、预定义效果等等。 阅读本节以了解 Unity 中的音频,包括剪辑、声源、侦听器、导入和声音设置。 相关教程: 音频 相关的提示、技巧和故障排除,等参阅 音频知识库 部分。

  • Audio接口仅适用于780和更高版本的手机QQ,如需在780以下版本使用音频功能,请使用原来的接口 音频播放接口分为普通音频接口(normal)和音效接口(effect)。普通接口和老接口类似,支持play,pause等方法,以及各种属性和事件(详情参考文档末尾的表)。effect接口用于播放短时,高频的音效,建议尽可能复用同一个对象来播放音频。ios只能播放,停止音效。android可以播放,

  • InnerAudioContext jd.createInnerAudioContext() 创建内部 audio 上下文 InnerAudioContext 对象。 返回值 InnerAudioContext InnerAudioContext InnerAudioContext 实例,可通过 jd.createInnerAudioContext 接口获取实例。 属性 string src 音频

  • 问题内容: 我正在设计一个简单的调谐器,所以我的目标是显示音符名称(A,B,F#)以及理论声音和实际输入之间的 距离( 以分为单位)。 我是音频和信号处理的新手,所以我做了一些研究,发现 了一个 叫做快速傅立叶变换 的东西 ,它可以分析字节并给我频率。另外,我发现了一些Java库,例如通用数学和JTransforms,所以我不会自己编写硬代码。 我相信就这样,因为每个范围的频率都可以以相同的气质直