Skip to content

Instantly share code, notes, and snippets.

@thehunmonkgroup
Last active January 22, 2023 15:04
Show Gist options
  • Save thehunmonkgroup/2c3be48a751f6b306f473d14eaa796a0 to your computer and use it in GitHub Desktop.
Save thehunmonkgroup/2c3be48a751f6b306f473d14eaa796a0 to your computer and use it in GitHub Desktop.
/**
* Illustrates how to clone and manipulate MediaStream objects.
*/
function makeAudioOnlyStreamFromExistingStream(stream) {
var audioStream = stream.clone();
var videoTracks = audioStream.getVideoTracks();
for (var i = 0, len = videoTracks.length; i < len; i++) {
audioStream.removeTrack(videoTracks[i]);
}
console.log('created audio only stream, original stream tracks: ', stream.getTracks());
console.log('created audio only stream, new stream tracks: ', audioStream.getTracks());
return audioStream;
}
function makeVideoOnlyStreamFromExistingStream(stream) {
var videoStream = stream.clone();
var audioTracks = videoStream.getAudioTracks();
for (var i = 0, len = audioTracks.length; i < len; i++) {
videoStream.removeTrack(audioTracks[i]);
}
console.log('created video only stream, original stream tracks: ', stream.getTracks());
console.log('created video only stream, new stream tracks: ', videoStream.getTracks());
return videoStream;
}
function handleSuccess(stream) {
var audioOnlyStream = makeAudioOnlyStreamFromExistingStream(stream);
var videoOnlyStream = makeVideoOnlyStreamFromExistingStream(stream);
// Do stuff with all the streams...
}
function handleError(error) {
console.error('getUserMedia() error: ', error);
}
var constraints = {
audio: true,
video: true,
};
navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(handleError);
@fippo
Copy link

fippo commented Sep 4, 2018

makeAudioOnlyStreamFromExistingStream should work as new MediaStream(stream.getAudioTracks() which is better than cloning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment