0

I'm trying to create a .webm file from a canvas. To do this I'm using captureStream and MediaRecorder. However, I'm having issues as the ondataavailable event only gets fired when the MediaRecorder is stopped, and the event data it contains is size 0.

I've been following these guides to help implement this:

Here are the relevant parts of my code (you can see the full code too):

On init:

this.displayCanvas = this.$element.find('canvas')[0];
this.bufferCanvas = document.createElement("canvas");
this.backgroundCanvas = document.createElement("canvas");
this.context = this.displayCanvas.getContext("2d");
this.bufferContext = this.bufferCanvas.getContext("2d");
this.backgroundContext = this.backgroundCanvas.getContext("2d");
// recording stream
this.stream = this.displayCanvas.captureStream(25);
console.log("Stream started: ", this.stream);

Drawing:

this.context.drawImage(this.backgroundCanvas, 0, 0);
this.context.drawImage(this.bufferCanvas, this.scrollOffset, -400);

Capture start:

var options = {mimeType: 'video/webm'};
this.recording = true;

recordedChunks = [];
mediaRecorder = new MediaRecorder(this.stream, options);
mediaRecorder.ondataavailable = this.captureDataAvailable;
mediaRecorder.start(100);

On data available:

captureDataAvailable: function(event) {
    console.log('data available: ');
    console.log(event.data);
    if(event.data.size > 0) {
        console.log('writing');
        recordedChunks.push(event.data);
    }
}

Capture finished:

mediaRecorder.stop();
console.log(recordedChunks.length);
var blob = new Blob(recordedChunks, {type: 'video/webm'});
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'Waterpipe-' + Math.round(new Date().getTime()/1000) + '.webm';
document.body.appendChild(a);
a.click();
//window.URL.revokeObjectURL(url);
//document.body.removeChild(a);

this.recording = false;

Any help with this issue would be much appreciated.

Peter Gordon
  • 1,075
  • 1
  • 18
  • 38
  • Call the finish part on the onstop handler of your MediaRecorder. – Kaiido Oct 05 '18 at 11:49
  • My issue turned out to be that when the canvas changes size, I had to reopen the window. Just reloading the page didn't seem to be enough. I also took your advice @Kaiido, thanks! – Peter Gordon Oct 05 '18 at 12:17

0 Answers0