Skip to content

Instantly share code, notes, and snippets.

@grishgrigoryan
Created July 4, 2018 13:56
Show Gist options
  • Save grishgrigoryan/ee2dd5c20edd384eb0f22ca5584748b6 to your computer and use it in GitHub Desktop.
Save grishgrigoryan/ee2dd5c20edd384eb0f22ca5584748b6 to your computer and use it in GitHub Desktop.
StreamMixer helps to play with MediaStream: Merge multiple streams into single one ( can be used with WebRtc to send multiple streams over a single WebRTC MediaConnection, or to switch streams without worrying about renegotiation)
export class StreamMixer {
streams: Array<{
id: string,
audioSource: any,
gainNode: any,
mediaStream: MediaStream
}>;
destination: any;
audioCtx: any;
constructor() {
this.streams = [];
this.audioCtx = new AudioContext();
this.destination = this.audioCtx.createMediaStreamDestination();
}
get stream() {
return this.destination.stream;
}
addStream(mediaStream): void {
try {
const id = mediaStream.id;
const audioSource = this.audioCtx.createMediaStreamSource(mediaStream);
const gainNode = this.audioCtx.createGain();
audioSource.connect(gainNode);
gainNode.connect(this.destination);
this.streams.push({ id, audioSource, gainNode, mediaStream });
} catch (e) {
console.error(e);
}
}
removeStream(mediaStream): void {
for (let i = 0; i < this.streams.length; i++) {
if (this.streams[i].id == mediaStream.id) {
this.streams[i].audioSource = null;
this.streams[i].gainNode.disconnect(this.destination);
this.streams[i].gainNode = null;
this.streams[i] = null;
this.streams.splice(i, 1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment