How to remove video/audio tracks from MediaStream in WebRTC

Table of contents
Reading Time: 2 minutes

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 tech enthusiast with having around 10 years of experience who loves to solve complex problems with pure quality. He is a functional programmer and loves to learn new trending technologies. His leadership skill is well prooven and has delivered multiple distributed applications with high scalability and availability by keeping the Reactive principles in mind. He is well versed with Scala, Akka, Akka HTTP, Akka Streams, Java8, Reactive principles, Microservice architecture, Async programming, functional programming, distributed systems, AWS, docker.

1 thought on “How to remove video/audio tracks from MediaStream in WebRTC2 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading