浏览器音频的 Hz 检测不准确
Inaccurate Hz detection of browser audio
import PitchFinder from 'pitchfinder'
const detectPitch = PitchFinder.AMDF()
const notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'G', 'G#']
export default {
data () {
return {
note: 'A',
register: 4,
cents: 0
}
},
mounted () {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const context = new AudioContext()
const source = context.createMediaStreamSource(stream)
const processor = context.createScriptProcessor()
source.connect(processor)
processor.connect(context.destination)
processor.onaudioprocess = e => {
const hz = detectPitch(e.inputBuffer.getChannelData(0))
if (hz) {
console.log(hz)
// ¢ or c = 1200 × log2 (f2 / f1), 1 semitone = 100 cents
const semitones = 12 * (Math.log2((hz) / 440))
const cents = semitones * 100
// TODO: update component
}
}
})
.catch(e => {
// TODO: handle error
})
}
}
}
我的 Vue 组件中有上述代码(请注意,只有一些与 Vue 相关的代码附加在上下文中。)我遇到了打印到控制台的值不准确的问题。我使用了一架无人机,并通过其他知名调谐器 (A = 440 Hz) 验证了它的音高。当用我的代码打印控制台时,赫兹总是 ~404,其他音高也被偏移。这是为什么?谢谢
您代码中其他地方的采样率有误。
440 * 44100.0/48000.0 = 404.25
我的猜测是您 运行 您的音频输入为 48 kHz,但音调检测器认为采样率为 44.1 kHz。
import PitchFinder from 'pitchfinder'
const detectPitch = PitchFinder.AMDF()
const notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'G', 'G#']
export default {
data () {
return {
note: 'A',
register: 4,
cents: 0
}
},
mounted () {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const context = new AudioContext()
const source = context.createMediaStreamSource(stream)
const processor = context.createScriptProcessor()
source.connect(processor)
processor.connect(context.destination)
processor.onaudioprocess = e => {
const hz = detectPitch(e.inputBuffer.getChannelData(0))
if (hz) {
console.log(hz)
// ¢ or c = 1200 × log2 (f2 / f1), 1 semitone = 100 cents
const semitones = 12 * (Math.log2((hz) / 440))
const cents = semitones * 100
// TODO: update component
}
}
})
.catch(e => {
// TODO: handle error
})
}
}
}
我的 Vue 组件中有上述代码(请注意,只有一些与 Vue 相关的代码附加在上下文中。)我遇到了打印到控制台的值不准确的问题。我使用了一架无人机,并通过其他知名调谐器 (A = 440 Hz) 验证了它的音高。当用我的代码打印控制台时,赫兹总是 ~404,其他音高也被偏移。这是为什么?谢谢
您代码中其他地方的采样率有误。
440 * 44100.0/48000.0 = 404.25
我的猜测是您 运行 您的音频输入为 48 kHz,但音调检测器认为采样率为 44.1 kHz。