opentok / opentok-react

React components for OpenTok.js
https://www.npmjs.com/package/opentok-react
MIT License
107 stars 105 forks source link

Correct way to determine which audio source is selected (label comparison doesn't work with "Default - ") #187

Open k-funk opened 3 years ago

k-funk commented 3 years ago

(Sorry if this isn't the best repo to post in, this question is regarding @opentok/client. If y'all have another place I should ask this question, please let me know!)

I'm working on making a dropdown very similar to https://opentok.github.io/opentok-web-samples/Publish-Devices/, but also trying to make it dynamic such that if you connect a new device, the list of options and the currently selected device is shown (that functionality is not in the example).

I've almost achieved this here (this isn't my exact code, but a simplified example):

navigator.mediaDevices?.addEventListener('devicechange', () => {
  OT.getDevices((err, devices) => {
    const audioDevices: OT.Device[] = devices?.filter((device) => device.kind === 'audioInput') ?? []
    const currentMediaTrack: MediaStreamTrack = videoChatController?.publisher?.getAudioSource()
    // this is the problem
    const currentDevice = audioDevices?.find((audioDevice: OT.Device) => audioDevice.label === device?.label)

    // then, with react, i render a dropdown picker, with the list of `audioDevices` as the user's options, and `currentDevice` as the one that is chosen
  })
})

I based this code on https://tokbox.com/developer/guides/audio-video/js/, but the example seems fragile/wrong, particularly, this line:

if (device.label === publisher.getAudioSource().label) {

The label (string) of a given device can change if the OSs default input source changes.. Example: 'Default - John Doe’s AirPods (Bluetooth)' will become 'John Doe’s AirPods (Bluetooth), or vice versa, in which case the device will not be found in the list of audioDevices. OSs can change the primary (default) input source if you, for example, take off your airpods, or if you manually change the input source, both without disconnecting that audio source.

Normally I'd compare something actually unique, like ids of MediaStreamTracks and OT.Devices, but those two id's are different, so that comparison also won't work. The best solution I can think of is to do something hacky like trim 'Default - ' before doing comparisons, but that seems terrible and possibly chrome or OS specific.

k-funk commented 3 years ago

FWIW, for anyone else reading this. I messaged tokbox support, and the response I got today was

I've received confirmation from our Product and Engineering teams that removing the "Default -" label is the approach that needs to be taken for this scenario and we do not currently have any additional workaround.