[英]Read frequency from mic on Raspberry Pi
有沒有一種簡單的方法來錄制幾秒鍾的聲音並將其轉換為頻率? 我有一個USB麥克風和一個覆盆子pi 2 B.
在發布的文件(convert2note.py)中,我想知道如何使f等於從麥克風獲得的頻率。 這是該程序到目前為止的樣子
#d=69+12*log(2)*(f/440)
#d is midi, f is frequency
import math
f=raw_input("Type the frequency to be converted to midi: ")
d=69+(12*math.log(float(f)/440))/(math.log(2))
d=round(int(d))
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
print notes[d % len(notes)]
非常感謝提前:D
為了捕獲音頻,您可以使用sox
程序。 有關詳細信息,請參閱鏈接的文檔,但它可以很簡單:
rec input.wav
但以下用於使文件與下面的代碼所期望的格式匹配;
rec −c 2 −b 16 −e signed-integer -r 44100 input.wav
(從技術上講,只需要-c
, -b
和-e
選項來匹配下面的代碼。您可以降低采樣率-r
以加快處理速度)
為了在Python中處理音頻,最好將其保存在wav
文件中,因為Python有一個用於讀取標准庫中的模塊的模塊。
為了將音頻轉換為頻率,我們將使用Numpy 快速傅立葉變換形式的離散 傅立葉變換進行實際輸入 。 請參閱下面的代碼片段,其中我也使用matplotlib來繪制圖表。
下面的代碼假設一個2聲道(立體聲)16位WAV文件。
from __future__ import print_function, division
import wave
import numpy as np
import matplotlib.pyplot as plt
wr = wave.open('input.wav', 'r')
sz = wr.getframerate()
q = 5 # time window to analyze in seconds
c = 12 # number of time windows to process
sf = 1.5 # signal scale factor
for num in range(c):
print('Processing from {} to {} s'.format(num*q, (num+1)*q))
avgf = np.zeros(int(sz/2+1))
snd = np.array([])
# The sound signal for q seconds is concatenated. The fft over that
# period is averaged to average out noise.
for j in range(q):
da = np.fromstring(wr.readframes(sz), dtype=np.int16)
left, right = da[0::2]*sf, da[1::2]*sf
lf, rf = abs(np.fft.rfft(left)), abs(np.fft.rfft(right))
snd = np.concatenate((snd, (left+right)/2))
avgf += (lf+rf)/2
avgf /= q
# Plot both the signal and frequencies.
plt.figure(1)
a = plt.subplot(211) # signal
r = 2**16/2
a.set_ylim([-r, r])
a.set_xlabel('time [s]')
a.set_ylabel('signal [-]')
x = np.arange(44100*q)/44100
plt.plot(x, snd)
b = plt.subplot(212) # frequencies
b.set_xscale('log')
b.set_xlabel('frequency [Hz]')
b.set_ylabel('|amplitude|')
plt.plot(abs(avgf))
plt.savefig('simple{:02d}.png'.format(num))
plt.clf()
avgf
陣列現在保持左右頻率的平均值。 情節看起來像這樣;
如您所見,聲音信號通常包含許多頻率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.