如何在React中使用audioWorklet.addModule?

时间:2018-11-08 22:06:18

标签: javascript reactjs audio web-audio-api audiocontext

我已经开始尝试使用Web Audio API

创建一个可在React中使用的录音机

这是我的Recorder类的代码

import AudioNode from './workletNode'


export default class Recorder {
  constructor(context) {

    this.context = context
    this.recording = false

    console.log(context)

    context.audioWorklet.addModule('processor.js')
      .then(() => {
        console.log('added worklet module')

        navigator.mediaDevices.getUserMedia({audio: true, video: false})
          .then(stream => {
            console.log('Have stream')
            let microphone = context.createMediaStreamSource(stream)
            let wavEncoder = new AudioNode(context)

            microphone.connect(wavEncoder).connect(context.destination)
          })
      })
      .catch((e) => {
        alert('Error getting audio')
        console.log(e)
      })
  }


  record() {
    console.log('Start recorder')
    this.recording = true
  }

  stop() {
    console.log('Stop recorder')
    this.recording = false
  }
}

我遇到的问题是与此行:context.audioWorklet.addModule('processor.js')

没有添加processor.js文件。

,然后在到达此行时引发错误:

let wavEncoder = new AudioNode(context)

错误是:

未处理的拒绝(TypeError):__WEBPACK_IMPORTED_MODULE_0__workletNode ___ default.a不是构造函数

我已经在react之外尝试了相同的代码,这很好。因此,这与在react中使用audioWorklet.addModule有关。

有人可以帮忙吗?

这是调用记录器的react组件:

import React from 'react'
import {connect} from 'react-redux'
import {Button} from 'semantic-ui-react'
import {injectIntl} from 'react-intl'
import Recorder from './recorder'

class SpeechToTextAudioWorklet extends React.Component {

  componentDidMount() {
    this.context = null
    this.recorder = null
  }

  startRecorder() {
    if (!this.context) {
      this.context = new window.AudioContext()
      this.recorder = new Recorder(this.context)
    } else {
      this.context.resume()
    }

    this.recorder && this.recorder.record()
  }

  stopRecorder() {
    this.recorder && this.recorder.stop()
  }

  render() {

    return (<div>Speech to text

      <Button id="start" onClick={() => {
        this.startRecorder()
      }}>Record</Button>
      <Button id="stop" onClick={() => {
        this.stopRecorder()
      }}>Stop</Button>
      <div id="recordingslist"></div>
    </div>)
  }
}

const mapStateToProps = () => {
  return {}
}

export default connect(
  mapStateToProps
)(injectIntl(SpeechToTextAudioWorklet))

1 个答案:

答案 0 :(得分:0)

尝试在worklet文件夹中建立一个public目录,将AudioWorkletProcesser移到那里,然后更改代码以反映新路径:context.audioWorklet.addModule('worklet/processor.js')