【发布时间】:2012-09-02 22:07:38
【问题描述】:
我正在尝试使用 this 节拍检测算法在 python 中进行音频处理。我已经实现了上述文章中的第一个(非优化版本)。虽然它会打印一些结果,但我无法检测它是否能以某种准确度工作,因为我不知道如何用它播放声音。
目前,我正在使用Popen 在进入计算循环之前用歌曲异步启动我的媒体播放器,但我不确定这种策略是否有效并给出同步结果。
#!/usr/bin/python
import scipy.io.wavfile, numpy, sys, subprocess
# Some abstractions for computation
def sumsquared(arr):
sum = 0
for i in arr:
sum = sum + (i[0] * i[0]) + (i[1] * i[1])
return sum
if sys.argv.__len__() < 2:
print 'USAGE: wavdsp <wavfile>'
sys.exit(1)
numpy.set_printoptions(threshold='nan')
rate, data = scipy.io.wavfile.read(sys.argv[1])
# Beat detection algorithm begin
# the algorithm has been implemented as per GameDev Article
# Initialisation
data_len = data.__len__()
idx = 0
hist_last = 44032
instant_energy = 0
local_energy = 0
le_multi = 0.023219955 # Local energy multiplier ~ 1024/44100
# Play the song
p = subprocess.Popen(['audacious', sys.argv[1]])
while idx < data_len - 48000:
dat = data[idx:idx+1024]
history = data[idx:hist_last]
instant_energy = sumsquared(dat)
local_energy = le_multi * sumsquared(history)
print instant_energy, local_energy
if instant_energy > (local_energy * 1.3):
print 'Beat'
idx = idx + 1024
hist_last = hist_last + 1024 # Right shift history buffer
p.terminate()
为了以时间同步的方式获得音频输出和算法(控制台)输出,我可以对脚本进行哪些修改/添加?即当控制台输出特定帧的结果时,该帧必须在扬声器上播放。
【问题讨论】:
-
你可以将
sumsquared改写为一行:return (arr**2).sum()。这会将所有这些计算下推到 C 代码中,并且可能会更快。
标签: python audio-processing beat-detection