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:
- https://webrtc.github.io/samples/src/content/capture/canvas-record/
- https://developers.google.com/web/updates/2016/01/mediarecorder
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.