如何使用Reactjs或Javascript转换WAV文件中的音频块?

时间:2019-06-03 00:05:15

标签: javascript reactjs voice-recognition voice mediarecorder

我正在使用带有Reactjs前端的VUI界面。我有一个可以播放的BLOB文件,但我想使用REACT或Javascript将其转换为.WAV文件,以将其发送到服务器。

我尝试了很多事情,但没有找到解决方法

toggleRecording() {
    if (this.state.start === 1) {
      console.log("we start recording", this.state.start)
      this.setState({ start: 0, recognition: "" })

      const constraints = {
        audio: {
          sampleRate: 16000,
          channelCount: 1,
        }
      }

      navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
          console.log(this);
          this.recorder = new MediaRecorder(stream);
          this.recorder.start();

          const audioChunks = [];
          this.recorder.addEventListener("dataavailable", event => {
            audioChunks.push(event.data);
          });

          this.recorder.addEventListener("stop", () => {
            const audioBlob = new Blob(audioChunks, { 'type': 'audio/wav' });

            const audioUrl = URL.createObjectURL(audioBlob);

            console.log("test: ", audioUrl)
            console.log(audioBlob.type)

            fetch('http://127.0.0.1:6060/api/sendaudio', {
              method: "post",
              headers: { 'Content-Type': 'audio/wav' },
              body: audioBlob
            })
              .then(response => {
                return response.text()
              }).then(text => {
                console.log(text);
                this.setState({ recognition: text })
              });

            //to play the audio file:
            const audio = new Audio(audioUrl);
            audio.play();
          });
        });
    }

我希望将Wav文件发布到我的服务器上,但不知道该怎么做...。

1 个答案:

答案 0 :(得分:0)

如果您在添加新依赖项时没有问题,可以尝试使用此软件包:https://www.npmjs.com/package/audiobuffer-to-wav

希望它会为您服务