是否可以从.wav文件创建MediaStream?

时间:2019-03-17 13:44:19

标签: javascript webrtc audio-recording

我目前有一个函数,可以从navigator.getUserMedia()接收MediaStream,效果很好。我想提供一个选项,可以上传音频文件并通过相同的功能模拟它。我想知道是否可以上传音频文件并创建一个Mediastream对象,并将其通过以下函数传递?

    startUserMedia(stream) {
    this.setState({ audio: stream });
    var audioContext = new AudioContext();
    var source = audioContext.createMediaStreamSource(stream);
    var processor = audioContext.createScriptProcessor(8192, 1, 1);

    source.connect(processor);
    processor.connect(audioContext.destination);

    const that = this;
    let audioBuffers = [];
    this.setState({ currentDuration: 0 });
    processor.onaudioprocess = function(e) {
      // Do something with the data, i.e Convert this to WAV
      if (that.state.currentDuration < that.state.chunkDuration) {
        that.setState({
          currentDuration: that.state.currentDuration + e.inputBuffer.duration
        });

        resampler(e.inputBuffer, 16000, function(event) {
          const buffer = event.getAudioBuffer();
          if (that.state.voiceActive) {
            audioBuffers.push(buffer);
          }
        });
      } else {
        if (!that.state.voiceActive) {
          that.mergeAndSendAudio(audioBuffers, audioContext);
          that.setState({ currentDuration: 0 });
          audioBuffers = [];
          audioBuffers.push(e.inputBuffer);
        } else {
          audioBuffers.push(e.inputBuffer);
        }
      }
    };

    var options = {
      onVoiceStart: function() {
        console.log("voice start");
        that.setState({ voiceActive: true });
      },
      onVoiceStop: function() {
        console.log("voice stop");
        that.setState({ voiceActive: false });
      },
      onUpdate: function(val) {
        // console.log('curr val:', val);
      }
    };
    vad(audioContext, stream, options);
  }

1 个答案:

答案 0 :(得分:0)

找到答案:

  handleselectedFile = event => {
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0
    });

    const objectURL = window.URL.createObjectURL(event.target.files[0]);
    const audio = new Audio(objectURL);
    const stream = audio.captureStream();

    audio.play().then(_ => {
      this.startUserMedia(stream);
    }); // stream now has input
  };