js录音实现实时录音音量大小实时分析

基于elctron+vue+ts实现的录音音量实时分析,给用户一个友好交互提示。


BE16A2F4-CDB9-46A5-8227-573EF6690F3A.png
15C06CDD-EADB-4666-A10B-182E6B11DAC1.png

核心片段分享:

const status = remote.systemPreferences.getMediaAccessStatus('microphone')
if (status == 'granted') {
  const constrains = { audio: true }
  navigator.mediaDevices
    .getUserMedia(constrains)
    .then((stream) => {
      // console.log(stream)
      this.openRecordSuccess(stream)
    })
    .catch((err) => {
      this.openRecordError(err)
    })
}
openRecordSuccess(stream: unknown): void {
    this.audioContext = new AudioContext()
    this.analyser = this.audioContext.createAnalyser()
    this.microphone = this.audioContext.createMediaStreamSource(stream as MediaStream)
    this.recordEventNode = this.audioContext.createScriptProcessor(2048, 1, 1)
    this.analyser.smoothingTimeConstant = 0.8
    this.analyser.fftSize = 1024
    this.microphone.connect(this.analyser)
    this.analyser.connect(this.recordEventNode)
    this.recordEventNode.connect(this.audioContext.destination)
    this.recordEventNode.addEventListener('audioprocess', this.analyzeMicrophoneVolume)
}
  openRecordError(error: unknown): void {
    console.log('访问用户媒体设备失败:', error)
  }
  analyzeMicrophoneVolume(): void {
    const array = new Uint8Array(this.analyser.frequencyBinCount)
    this.analyser.getByteFrequencyData(array)
    let values = 0
    const length = array.length
    for (let i = 0; i < length; i++) {
      values += array[i]
    }
    const average = values / length
    this.recordVolume = average
    // console.log('音量大小:' + Math.round(average))
  }

你可能感兴趣的:(js录音实现实时录音音量大小实时分析)