Created
November 16, 2018 22:39
-
-
Save bradley/2899a0125bb3a0c200754391493351b8 to your computer and use it in GitHub Desktop.
Useful for creating user media streams and tearing them back down.
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
// 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