javascriptreactjsget-display-media

How to download the video recorded with getDisplayMedia api?


Problem: In my React application, I have setup screen recording within the application using navigator.mediaDevices.getDisplayMedia when I set the stem to video tag and play it was playing successfully. But when I try to save it to a local machine it saving only 0 minutes of video.

This is my code.

const VideoCall = ({ match }) => {
    const { params: { campaignPatienId, userId, id, meetingId, videoId } } = match;
    const [mediaR,setMediaR] = useState(null);
    const [recordingStarted,setRecordingStarted] = useState(false)
  
    const handleRecording = async () =>{
        const videoElem = document.querySelector("video");
        var displayMediaOptions = {
            video: {
              cursor: "always"
            },
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                sampleRate: 44100
            }
          };
          try {
            navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then((strem)=>{
                console.log(strem,"stream")
                videoElem.srcObject = strem;
                setRecordingStarted(true)
                let mediaRecorder = new MediaRecorder(strem);
                
                let chunks = [];
                videoElem.onloadedmetadata= (e) =>{
                    videoElem.play();
                }

                mediaRecorder.ondataavailable = function (ev) {
                    console.log({ev})
                    chunks.push(ev.data)
                }
                mediaRecorder.onstop = (ev) => {
                    // window.clearTimeout(timoutStop);
                    let blob = new Blob(chunks, { type: "video/mp4" });
                    console.log(blob,"blob")
                    chunks = [];
                    strem.getTracks().forEach(function (track) {
                        track.stop();
                    });
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    document.body.appendChild(a);
                    a.style = 'display: none';
                    a.href = url;
                    a.download = 'test.mp4';
                    a.click();
                    window.URL.revokeObjectURL(url);

                }

                mediaRecorder.start();
                setMediaR(mediaRecorder)
            });
            
          } catch(err) {
            console.error("Error: " + err);
          }
    }


    const stopRecording = async () =>{
      let currentRecorder = mediaR;
      if (currentRecorder.state != "inactive") {
        await currentRecorder.stop();
      }
    }


    return (
        <div className="row" style={{ height: '100%', width: '100%' }}>
            <div className="col-md-12" >
                <div className="row">
                    <div className="colHeader">
                        <h3>Chat with Client</h3>
                        <div class="create-user-button" >
                            <Link
                                to="/mychat">
                                Go to Chat Screen
                                </Link>
                        </div>
                        <div>
                        {recordingStarted ?  <button
                            type="button"
                            onClick={() => stopRecording()}
                            className="btn btn-default scoreOverview"
                        >
                           Download
                        </button>:  <button
                            type="button"
                            onClick={() => handleRecording()}
                            className="btn btn-default scoreOverview"
                        >
                           Record Video Call
                        </button>}
                       
                        </div>
                    </div>
                </div>
                <video id="video" autoplay width="100%"></video>
                
                
            </div>
        </div>
    )
}

export default withRouter(VideoCall)

Can someone help me to solve this problem? .I tried a lot but it always downloads 0 minutes video.


Solution

  • WebRTC (getDisplayMedia) typically records as webm.

    I have a sample app running at record.a.video

    and in the code (which looks similar to yours, but for the mimetype): https://github.com/dougsillars/recordavideo/blob/main/public/index.js#L652

    function download() {
        var blob = new Blob(recordedBlobs, {type: 'video/webm'});
        var url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = 'test.webm';
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }, 100);
    }