Skip to content

Instantly share code, notes, and snippets.

@bradley
Created November 16, 2018 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradley/a40d0bf755e7c58a196f81ec2c3040df to your computer and use it in GitHub Desktop.
Save bradley/a40d0bf755e7c58a196f81ec2c3040df to your computer and use it in GitHub Desktop.
Useful for building recording from a user media stream.
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