javascriptmediastream

How to make and add a MediaStreamTrack to a media stream


I am wondering how to make and add a MediaStreamTrack to a MediaStream. I cant find a way to add or make one, and so I'm stuck. Please help. Thanks!


Solution

  • Step 1: Generate the tracks.

    
    const userMedia = await navigator.mediaDevices.getUserMedia({audio : true, video : true});
    
    const videoTrack = userMedia.getVideoTracks()[0];
    const audioTrack = userMedia.getAudioTracks()[0];
    
    

    Step 2: Create a MediaStream and add tracks to them.

    
    const stream = new MediaStream();
    stream.addTrack(videoTrack);
    stream.addTrack(audioTrack);
    
    

    Now you can use that MediaStream as whatever you want.

    To render the stream in HTML, create a video element in your HTML and set it's id to "localVideo" (It's optional, set it whatever you want. To attach stream to that video element, use:

    
    const videoElement = document.getElementById("localVideo");
    videoElement.srcObject = userMedia;
    videoElement.play();
    
    

    Note : navigator.mediaDevices.getUserMedia also returns a MediaStream. So there is no difference about the mentality between Step 1 and Step 2.

    Important Note : If you set "muted" prop to false of video element, you can't autoplay it in most of cases. If you want to autoplay the video without any user interaction to window, you have to set muted true.

    If you want to get screen recording track, use:

    const screenMedia = await navigator.mediaDevices.getDisplayMedia();