Skip to content

Instantly share code, notes, and snippets.

@kkm
Created April 15, 2018 22:14
Show Gist options
  • Save kkm/60ce3479ad35d923bbff6e4e8f5ae25c to your computer and use it in GitHub Desktop.
Save kkm/60ce3479ad35d923bbff6e4e8f5ae25c to your computer and use it in GitHub Desktop.
Chrome MediaRecorder in H264
<!DOCTYPE html>
<head>
<script>
var recordedChunks = [];
var constraints = {
audio: true,
video: true
};
var mediaRecorder = null;
navigator.mediaDevices.getUserMedia(constraints).then(onMediaSuccess, function(errorCallback) {
console.log(errorCallback);
});
function onMediaSuccess(stream) {
try {
window.stream.getVideoTracks()[0].stop();
} catch (err) {}
window.stream = stream;
var gumVideo = document.querySelector('video#local');
gumVideo.src = window.URL.createObjectURL(stream);
}
function start() {
var options = {
mimeType: 'video/webm;codecs=H264'
};
mediaRecorder = new MediaRecorder(window.stream, options);
mediaRecorder.ondataavailable = onDataAvailable;
mediaRecorder.start(1000);
}
function stop() {
mediaRecorder.stop();
}
function onDataAvailable(event) {
if (event.data.size > 0) {  
recordedChunks.push(event.data);  
}
}
function download() { 
var blob = new Blob(recordedChunks, {  
type: 'video/webm' 
}); 
var url = URL.createObjectURL(blob); 
var a = document.createElement('a'); 
document.body.appendChild(a); 
a.style = 'display: none'; 
a.href = url; 
a.download = 'test.webm'; 
a.click(); 
window.URL.revokeObjectURL(url);
}
</script>
</head>
<body>
<button onclick="start()">record</button>
<button onclick="stop()">stop</button>
<button onclick="download()">download</button>
<br>
<video id="local" autoplay/>
</body>
</html>
@kkm
Copy link
Author

kkm commented Apr 15, 2018

It works in localhost or https only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment