how can i save videos in webm format instead of mkv format

Viewed 787

I need a help. I have a javascript code in my site that record videos and save them on the server. The format in which the videos are saved depends on the browser I am using, because if I use Opera or Chrome, the videos are saved in MKV format, if I use Firefox instead, the videos are saved in WEBM format. The problem is that the videos I save using Opera and Chrome (i.e. MKV) Firefox cannot read them, while Opera and Chrome read the WEBM videos generated with firefox without problems. How can I make Opera and Chrome also save videos in WEBM so I no longer have the problem? JavaScript code:

let constraintObj = { 
    audio: true, 
    video: { 
        facingMode: "user", 
        width: { min: 640, ideal: 1280, max: 1920 },
        height: { min: 480, ideal: 720, max: 1080 } 
    } 
}; 
// width: 1280, height: 720  -- preference only
// facingMode: {exact: "user"}
// facingMode: "environment"

//handle older browsers that might implement getUserMedia in some way
if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {};
    navigator.mediaDevices.getUserMedia = function(constraintObj) {
        let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }
        return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraintObj, resolve, reject);
        });
    }
}else{
    navigator.mediaDevices.enumerateDevices()
    .then(devices => {
        devices.forEach(device=>{
            console.log(device.kind.toUpperCase(), device.label);
            //, device.deviceId
        })
    })
    .catch(err=>{
        console.log(err.name, err.message);
    })
}

navigator.mediaDevices.getUserMedia(constraintObj)
.then(function(mediaStreamObj) {
    //connect the media stream to the first video element
    let video = document.querySelector('video');
    if ("srcObject" in video) {
        video.srcObject = mediaStreamObj;
    } else {
        //old version
        video.src = window.URL.createObjectURL(mediaStreamObj);
    }
    
    video.onloadedmetadata = function(ev) {
        //show in the video element what is being captured by the webcam
        video.play();
    };
    
    //add listeners for saving video/audio
    let start = document.getElementById('btnStart');
    let stop = document.getElementById('btnStop');
    let save = document.getElementById('btnSave');
    let vidSave = document.getElementById('vid2');
    let mediaRecorder = new MediaRecorder(mediaStreamObj);
    let chunks = [];
    var blob = null;
    document.getElementById("vid2").style.visibility = "hidden";
    document.getElementById("btnSave").style.visibility = "hidden";
    
    var contatore=0;
    var dontstop=0;
    

    save.addEventListener('click', (ev)=>{
        
     contatore = 0;
    const formData = new FormData();
     formData.append('video', blob);
     fetch('videoRec', {
        method: 'POST',
        body: formData
        })
        .then(response => { console.log('upload success, ');
        document.getElementById('response').innerHTML="Video salvato con successo, ";
        })
    .catch(error => {console.log('error');
        document.getElementById('response').innerHTML="Errore durante il caricamento del video. Riprova.";
    })
    
    });

    
    start.addEventListener('click', (ev)=>{
        
        dontstop=1;
        //if user already started video before, ask him if want to save that video before 
        //recording another video
        if(contatore!=0){
            var domanda=confirm("Il video appena registrato andrĂ  eliminato. Vuoi Procedere?");
            if (domanda === false) {
            exit;
            }    
        }

        //when user's recording, vid2 must be hidden
        if(document.getElementById("vid2").style.visibility=="visible"){
            document.getElementById("vid2").style.visibility="hidden";
            document.getElementById("btnSave").style.visibility="hidden";
            document.getElementById('response').innerHTML=" ";
        }

        //start recording
        mediaRecorder.start();
        console.log(mediaRecorder.state);

        //disable start button and enable stop button
        document.getElementById('btnStart').disabled=true;
        document.getElementById('btnStop').disabled=false;

        //contatore increments when user records, so if he starts another rec without stopping before
        //ask him if want to save the last video
        contatore++;
        var timeleft = 5; //video must be 120 seconds

        downloadTimer = setInterval(function(){
        if(timeleft <= 0){ 

            //after 120 seconds record will stops automatically
            clearInterval(downloadTimer); //the countdown disappared
            document.getElementById("countdown").innerHTML = "Finished";
            mediaRecorder.stop();
            console.log(mediaRecorder.state);

            document.getElementById('btnStart').disabled=false;
            document.getElementById('btnStop').disabled=true;


            video.onloadedmetadata = function(ev) {
        
            chunks.push(ev.data);
            };

            
            // vid2 appears
            document.getElementById("vid2").style.visibility = "visible";
            document.getElementById("btnSave").style.visibility = "visible";
             blob = new Blob(chunks, { 'type' : 'video/webm;' });
            chunks = [];
            let videoURL = window.URL.createObjectURL(blob);
            vidSave.src = videoURL;
            

            } else {
                //else countdown continues
        document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
            }
        timeleft -= 1;
        }, 1000)
                     
    })

    stop.addEventListener('click', (ev)=>{
        if(dontstop!=1){
            exit;
        }
        mediaRecorder.stop();
        console.log(mediaRecorder.state);
        document.getElementById('btnStart').disabled=false;
        document.getElementById('btnStop').disabled=true;
        clearInterval(downloadTimer);
        document.getElementById("countdown").innerHTML = "Finished";
        document.getElementById("vid2").style.visibility = "visible";
        document.getElementById("btnSave").style.visibility = "visible";
    });
    mediaRecorder.ondataavailable = function(ev) {
        chunks.push(ev.data);
    }
    mediaRecorder.onstop = (ev)=>{
        blob = new Blob(chunks, { 'type' : 'video/webm;' });
        chunks = [];
        let videoURL = window.URL.createObjectURL(blob);
        vidSave.src = videoURL;
        
    } 
})
.catch(function(err) { 
    console.log(err.name, err.message); 
});

Thank you very much! Gennaro

1 Answers

you can try to fix the mimetype to video/webm;codecs=VP8, it should work with any browser supporting MediaRecorder

Related