2021-04-03 11:06:39 +08:00
|
|
|
const stopMediaStreamTracks = (stream) => {
|
|
|
|
if (stream && typeof stream.getTracks === 'function') {
|
2022-04-05 05:09:35 +08:00
|
|
|
stream.getTracks().forEach((track) => {
|
2021-07-06 00:01:13 +08:00
|
|
|
if (typeof track.stop === 'function' && track.readyState !== 'ended') {
|
2021-04-03 11:06:39 +08:00
|
|
|
track.stop();
|
2021-07-06 00:01:13 +08:00
|
|
|
// Manually emit the event as a safeguard; Firefox doesn't fire it when it
|
|
|
|
// should with live MediaStreamTracks...
|
|
|
|
const trackStoppedEvt = new MediaStreamTrackEvent('ended', { track });
|
|
|
|
track.dispatchEvent(trackStoppedEvt);
|
2021-04-03 11:06:39 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2022-04-05 05:09:35 +08:00
|
|
|
};
|
2021-04-03 11:06:39 +08:00
|
|
|
|
2022-04-05 05:09:35 +08:00
|
|
|
const getAudioTracks = (stream) => {
|
|
|
|
if (stream) {
|
|
|
|
if (typeof stream.getAudioTracks === 'function') {
|
|
|
|
return stream.getAudioTracks();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof stream.getTracks === 'function') {
|
|
|
|
return stream.getTracks().filter((track) => track.kind === 'audio');
|
|
|
|
}
|
|
|
|
}
|
2021-04-03 11:06:39 +08:00
|
|
|
|
2022-04-05 05:09:35 +08:00
|
|
|
return [];
|
|
|
|
};
|
|
|
|
|
|
|
|
const getVideoTracks = (stream) => {
|
2021-04-03 11:06:39 +08:00
|
|
|
if (stream) {
|
|
|
|
if (typeof stream.getVideoTracks === 'function') {
|
2022-04-05 05:09:35 +08:00
|
|
|
return stream.getVideoTracks();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof stream.getTracks === 'function') {
|
|
|
|
return stream.getTracks().filter((track) => track.kind === 'video');
|
2021-04-03 11:06:39 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-05 05:09:35 +08:00
|
|
|
return [];
|
|
|
|
};
|
2021-04-03 11:06:39 +08:00
|
|
|
|
2022-04-05 05:09:35 +08:00
|
|
|
const getDeviceIdFromTrack = (track) => {
|
|
|
|
if (track && typeof track.getSettings === 'function') {
|
|
|
|
const { deviceId } = track.getSettings();
|
|
|
|
return deviceId;
|
|
|
|
}
|
|
|
|
return '';
|
|
|
|
};
|
|
|
|
|
|
|
|
const extractDeviceIdFromStream = (stream, kind) => {
|
2021-07-02 22:05:09 +08:00
|
|
|
// An empty string is the browser's default...
|
2022-04-05 05:09:35 +08:00
|
|
|
let tracks = [];
|
2021-07-02 22:05:09 +08:00
|
|
|
|
2022-04-05 05:09:35 +08:00
|
|
|
switch (kind) {
|
|
|
|
case 'audio':
|
|
|
|
tracks = getAudioTracks(stream);
|
|
|
|
return getDeviceIdFromTrack(tracks[0]);
|
|
|
|
case 'video':
|
|
|
|
tracks = getVideoTracks(stream);
|
|
|
|
return getDeviceIdFromTrack(tracks[0]);
|
|
|
|
default: {
|
|
|
|
return '';
|
|
|
|
}
|
2021-07-02 22:05:09 +08:00
|
|
|
}
|
2022-04-05 05:09:35 +08:00
|
|
|
};
|
2021-07-02 22:05:09 +08:00
|
|
|
|
2021-04-03 11:06:39 +08:00
|
|
|
export default {
|
|
|
|
stopMediaStreamTracks,
|
|
|
|
getVideoTracks,
|
2022-04-05 05:09:35 +08:00
|
|
|
extractDeviceIdFromStream,
|
2021-04-03 11:06:39 +08:00
|
|
|
};
|