浏览器音频的Hz检测不准确

时间:2018-10-26 01:44:25

标签: audio pitch-detection

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)一起验证了其音高。当使用我的代码打印到控制台时,Hz始终为〜404,其他音高也会偏移。这是为什么?谢谢。

1 个答案:

答案 0 :(得分:1)

您的代码中其他地方的采样率错误。

440 * 44100.0/48000.0 = 404.25

我的猜测是您正在以48 kHz的频率运行音频输入,但是基音检测器认为采样率为44.1 kHz。

相关问题