Created
November 16, 2018 22:40
-
-
Save bradley/a40d0bf755e7c58a196f81ec2c3040df to your computer and use it in GitHub Desktop.
Useful for building recording from a user media stream.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StreamRecording { | |
constructor(stream, mimeTypes = StreamRecording.DefaultMimeTypes) { | |
this._stream = null; | |
this._mimeType = null; | |
this._recordedBlobs = []; | |
this._buildMediaRecorder(stream, mimeTypes); | |
} | |
get stream() { | |
return this._stream; | |
} | |
set stream() { | |
throw(Error("StreamRecorder error: stream may not be set by the user after initialization.")); | |
} | |
get mimeType() { | |
return this.mimeType; | |
} | |
set mimeType() { | |
throw(Error("StreamRecorder error: mimeType may not be set by the user after initialization.")); | |
} | |
start() { | |
if (this._mediaRecorder.state == "inactive") { | |
this._mediaRecorder.start(10); // Record in 10ms chunks. | |
} | |
} | |
pause() { | |
this._mediaRecorder.pause(); | |
} | |
resume() { | |
this._mediaRecorder.resume(); | |
} | |
stop() { | |
this._mediaRecorder.stop(); | |
} | |
clear() { | |
this._recordedBlobs = []; | |
} | |
toBlob() { | |
return new Blob(this._recordedBlobs, { type: this._mimeType }); | |
} | |
toUrl() { | |
return URL.createObjectURL(this.toBlob()); | |
} | |
_buildMediaRecorder(stream, mimeTypes) { | |
if (!stream || stream.constructor != MediaStream) { | |
throw(Error("StreamRecording error: stream must be of type MediaStream.")); | |
} | |
this._stream = stream; | |
this._mimeType = this._firstSupportedMimeType(mimeTypes); | |
this._mediaRecorder = new MediaRecorder(this._stream, { mimeType: this._mimeType }); | |
this._mediaRecorder.ondataavailable = this._handleRecordedDataAvailable; | |
} | |
_firstSupportedMimeType(mimeTypes) { | |
const mimeTypesArray = Array.isArray(mimeTypes) ? mimeTypes : Array.of(mimeTypes); | |
const mimeType = mimeTypesArray.find(mimeType => MediaRecorder.isTypeSupported(mimeType)); | |
if (!mimeType) { | |
throw(Error("StreamRecording error: no received mimeType supported by MediaRecorder.")); | |
} | |
return mimeType; | |
} | |
_handleRecordedDataAvailable({data}) { | |
if (data && data.size > 0) { | |
this._recordedBlobs.push(data); | |
} | |
} | |
} | |
StreamRecording.DefaultMimeTypes = [ | |
"video/webm;codecs=vp9", | |
"video/webm;codecs=vp8", | |
"video/webm" | |
]; | |
export default StreamRecording; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment