Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a MediaStream from a .wav File?

Tags:

I currently have a function which receives a MediaStream from navigator.getUserMedia(), which works great. I would like to give the option to upload an audio file and mimic it going through the same function. I was wondering whether it would be possible to upload an audio file and create a Mediastream object and pass it through the below function?

    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);
  }
like image 558
maitham dib Avatar asked Mar 17 '19 13:03

maitham dib


1 Answers

Found the answer:

  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
  };
like image 87
maitham dib Avatar answered Oct 19 '22 18:10

maitham dib