Whoa! I’m recording video and audio in my PWA app now! This is so crazy..

Turns out there is a MediaStream Recording API, so I’m putting it to good use on my PWA Sensors course (it will appear here one day).

Dude! I’m actually recording a video note - with audio - in-browser on my SurfaceBook at my local Maccas McCafe!

Recording a video in a PWA

There’s an awesome Mozilla post that gives you a good nuts and bolts of the API - which I found super helpful.

The MediaRecorder stuff really builds on the MediaStream stuff I was talking about last week.

You take an incoming stream, then feed it into a MediaRecorder. Call mediaRecorder.start() to start recording - in my case I supply a “ms chunk size” with .start(1000) so chunks of video will arrive in my callback every second. Once started, your ondataavailable handler will start getting chunks of video. How cool!

When you’re done recording, invoke mediaRecorder.stop() (which I do from a button click - not shown here).

Once you call stop() on the MediaRecorder to stop the recording, your onstop handler will get called back. You then take that nice selection of video chunks that we have accumulated in the array, and Blob() it into an object that we can URL-ize.

Finally, assign your Blob URL to a stock standard vanilla <video> component and click play to playback your video!

// find my <video> element in the DOM
const videoPreview = this.$.videoNote;

navigator.mediaDevices.getUserMedia(constraints)
    .then((stream) => {

        let mediaRecorder = new MediaRecorder(stream);

        // save for later so we can mediaRecorder.stop() from a button click
        this.set('mediaRecorder', mediaRecorder); 

        // Start with number of ms per "chunk"
        mediaRecorder.start(1000);
        
        let chunks = [];
        
        mediaRecorder.ondataavailable = function(e) {
                chunks.push(e.data);       
        }

        mediaRecorder.onstop = function(e) {
            var blob = new Blob(chunks, { 'type' : 'video/webm' });               
            videoPreview.src = URL.createObjectURL(blob);
        }

        
    }, (err) => {
        console.log('User rejected camera capture permissions', err);
    });
}

Constantly amazed at how much you can do in a browser these days.. Such an exciting time for PWAs.

Time to finish this script and get this module out the door later in the week.

Have fun!