How to remove video/audio tracks from MediaStream in WebRTC

WebRTC (Web Real-Time Communication) is an API definition drafted by the World Wide Web Consortium (W3C) that supports browser-to-browser applications for voice calling, video chat, and P2P file sharing without plugins.

Now in this blog, I am going to explain that if we have a mediastream containing both audio and video and at some point of time we want to remove one of the track i.e. either video or audio, then how can we do this.
First of all, we will get the mediastream by following code :

Here, as you can see, the option audio and video in above code both are true,

It means the mediastream which getUserMedia will capture will contain both audio and video.

Now we want to remove a track from mediastream. So for this we should have the reference of that mediastream first.
So now, we will define a global variable and when we will get the stream from getUserMedia, we will assign the stream to that variable.

To remove audio track :

To remove video track :

It will remove video track from mediastream but we will get a black screen.

If we want to remove black screen as well then we have 2 options for this.
1. Make css property display : none for video element.

OR
2. Add new mediastream URL (without video track) in audio element of HTML5 instead of video element and make src of video element to empty.

You can get full code here

Written by 

Rishi is a Lead Consultant, with experience of more than 7 years. Rishi is product focused developer who loves developing both front-end user interfaces and scalable back-end infrastructure. He is a good team player, quick learner and a humble person. He has good time management skills, aimed to give best results and fully dedicated towards his work & responsibilities. He is able to work as individual and as well as in team. He loves to share his knowledge, therefore he often writes technical blogs.

1 thought on “How to remove video/audio tracks from MediaStream in WebRTC

Leave a Reply

%d bloggers like this: