Search code examples
javascriptwebrtcwebapiweb-mediarecorder

Adding an AudioTrack while the MediaRecorder is in state 'recording'


Im trying to add mediaTrack to the mediaStream while MediaRecorder is in state 'recording'

The code for adding a new track is the following:

activeStream.addTrack(newAudioTrack)

After that the event (onstop) was triggered. How can I avoid this?


Solution

  • You can use an AudioContext to create a fixed MediaStream that you can pass to the MediaRecorder. This allows you to change the input when recording.

    const audioContext = new AudioContext();
    const mediaStreamAudioDestinationNode = new MediaStreamAudioDestinationNode(audioContext);
    const mediaRecorder = new MediaRecorder(mediaStreamAudioDestinationNode.stream);
    

    Let's say you have a MediaStream called initialMediaStream. You could connect it like that:

    const mediaStreamAudioSourceNode = new MediaStreamAudioSourceNode(
        audioContext,
        { mediaStream: initialMediaStream }
    );
    
    mediaStreamAudioSourceNode.connect(mediaStreamAudioDestinationNode);
    

    You can then start recording the initialMediaStream.

    mediaRecorder.start();
    

    Later on you can replace the initialMediaStream with anotherMediaStream.

    const anotherMediaStreamAudioSourceNode = new MediaStreamAudioSourceNode(
        audioContext,
        { mediaStream: anotherMediaStream }
    );
    
    anotherMediaStreamAudioSourceNode.connect(mediaStreamAudioDestinationNode);
    mediaStreamAudioSourceNode.disconnect();
    

    You could even use GainNodes to apply a cross-fade between the two streams if that's what you want.