我从傅立叶变换中得到了光谱。它看起来像这样:
警察刚刚从附近经过
颜色代表强度。
X轴是时间。
Y 轴是频率 - 其中 0 位于顶部。
虽然口哨或警笛只留下一条痕迹,但许多其他音调似乎包含很多谐波频率。
电吉他直接插入麦克风(标准调音)
真正糟糕的是,正如您所看到的,没有主要的强度 - 有 2-3 个频率几乎相等。
我编写了一个峰值检测算法来突出显示最重要的峰值:
function findPeaks(data, look_range, minimal_val) {
if(look_range==null)
look_range = 10;
if(minimal_val == null)
minimal_val = 20;
//Array of peaks
var peaks = [];
//Currently the max value (that might or might not end up in peaks array)
var max_value = 0;
var max_value_pos = 0;
//How many values did we check without changing the max value
var smaller_values = 0;
//Tmp variable for performance
var val;
var lastval=Math.round(data.averageValues(0,4));
//console.log(lastval);
for(var i=0, l=data.length; i<l; i++) {
//Remember the value for performance and readibility
val = data[i];
//If last max value is larger then the current one, proceed and remember
if(max_value>val) {
//iterate the ammount of values that are smaller than our champion
smaller_values++;
//If there has been enough smaller values we take this one for confirmed peak
if(smaller_values > look_range) {
//Remember peak
peaks.push(max_value_pos);
//Reset other variables
max_value = 0;
max_value_pos = 0;
smaller_values = 0;
}
}
//Only take values when the difference is positive (next value is larger)
//Also aonly take values that are larger than minimum thresold
else if(val>lastval && val>minimal_val) {
//Remeber this as our new champion
max_value = val;
max_value_pos = i;
smaller_values = 0;
//console.log("Max value: ", max_value);
}
//Remember this value for next iteration
lastval = val;
}
//Sort peaks so that the largest one is first
peaks.sort(function(a, b) {return -data[a]+data[b];});
//if(peaks.length>0)
// console.log(peaks);
//Return array
return peaks;
}
这个想法是,我遍历数据并记住一个大于 thresold 的值minimal_val
。如果下一个look_range
值小于所选值,则将其视为峰值。这个算法不是很聪明,但很容易实现。
但是,它无法分辨出哪个是字符串的主要频率,就像我预期的那样:
红点突出最强峰
这是一个 jsFiddle,看看它是如何工作的(或者说不工作)。