JSFiddle - React, Tailwind, and code Playground
by mattybalaam
HTML
<video controls autoplay="autoplay"></video>
<p class="message"></p>
<button>stop recording</button>
JavaScript
var recording = {
videoOptions: {
audio: true,
video: true
},
el_video: document.querySelector('video'),
el_Message: document.querySelector('.message'),
el_Button: document.querySelector('button'),
init: function(options){
this.startMediaStream()
},
startMediaStream: function(){
this.capture = navigator.mediaDevices.getUserMedia(this.videoOptions);
this.capture.then(this.mediaStreamSuccess.bind(this));
this.capture.catch(this.webcamErrorHandler);
},
webcamErrorHandler: function(e) {
this.el_Message.innerHTML = 'error: ' + e;
},
mediaStreamSuccess: function(mediaStream) {
this.mediaStream = mediaStream;
this.mediaStreamTracks = this.mediaStream.getTracks();
this.mediaRecorder = new MediaRecorder(this.mediaStream);
this.mediaRecorder.ondataavailable = this.mediaStreamHandler.bind(this);
this.el_video.src = window.URL.createObjectURL(this.mediaStream);
this.startVideoHandler();
},
startVideoHandler: function(){
this.mediaRecorder.start(30000);
this.el_Button.addEventListener('click', this.stopVideoHandler.bind(this));
},
stopVideoHandler: function(){
//does this order matter to create a valid file?
this.mediaStreamTracks.forEach(function(track) {
console.log(track);
track.stop();
});
this.mediaRecorder.stop();
},
mediaStreamHandler: function(dataavailable){
if (this.stopped !== true) {
this.el_Button.remove();
this.stopped = true;
this.mediaStreamCapture(dataavailable);
}
},
mediaStreamCapture: function(dataavailable) {
var blobURL = window.URL.createObjectURL(dataavailable.data)
this.playRecordedVideo(blobURL);
this.addDownloadLink(blobURL, dataavailable.data.size);
},
playRecordedVideo: function(blobURL){
...