Skip to content

Instantly share code, notes, and snippets.

@bradley
Created November 16, 2018 22:39
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/2899a0125bb3a0c200754391493351b8 to your computer and use it in GitHub Desktop.
Save bradley/2899a0125bb3a0c200754391493351b8 to your computer and use it in GitHub Desktop.
Useful for creating user media streams and tearing them back down.
// StreamManager
// Useful for creating user media streams and tearing them back down.
//
class StreamManager {
constructor() {
this._stream = null;
this._constraints = null;
}
get stream() {
return this._stream;
}
set stream() {
throw(Error("StreamManager error: stream may not be set by the user, please call `create`."));
}
get constraints() {
return this._constraints;
}
set constraints() {
throw(Error("StreamManager error: constraints may not be set by the user, please pass constraints when calling `create`."));
}
create(constraints) {
return new Promise((resolve, reject) => {
if (this._stream) {
this.teardown();
}
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
this._stream = stream;
this._constraints = constraints;
resolve(this._stream);
})
.catch(reject);
});
}
teardown() {
this._stream.getTracks().forEach(track => track.stop());
this._stream = null;
this._constraints = null;
}
}
export default StreamManager;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment