zabumba
zabumba

Reputation: 12402

WebRTC - How to change the audio track for a existing stream

I have a webRTC connection established with audio and video.

On the caller side, I'd like to change the audio input.

e.g. the User changes the audioinput from a dropdown list.

What's the workflow to substitute the audio track of an existing stream?

Can I add another audio track and make one active over the other? how?

Looks like I may need to call getUserMedia again passing constraints (?), which to my understanding comes to create a New mediaStream instances and not modify the existing.

Upvotes: 2

Views: 4919

Answers (2)

jonowles
jonowles

Reputation: 466

There is now a much simpler API for this operation: RTCRtpSender.replaceTrack().

It could look something like this:

const currentSenders = peerConnection.getSenders();

const currentAudioSender = currentSenders.find((s) => s.track.kind === 'audio');

currentAudioSender.replaceTrack(newAudioTrack);

Upvotes: 3

Lars Spaenij
Lars Spaenij

Reputation: 53

For us it looks something like this:

const replaceTrack = async (peerConnection, oldSender, track, stream) => {
  peerConnection.removeTrack(oldSender);

  const newSender = peerConnection.addTrack(track, stream);

  const localSdp = await peerConnection.createOffer({ offerToReceiveAudio: 1 });
  await peerConnection.setLocalDescription(reply);

  const response = await sendOffer(peerConnection.localDescription);

  const description = new RTCSessionDescription(response);
  peerConnection.setRemoteDescription(description);

  return newSender;
}

Upvotes: 2

Related Questions