How to switch audio and video input devices during calls on the Web platform with Express?
Web Desktop Device Switching
Audio and video input devices are identified by device ID (deviceId). Each audio and video device has a unique device ID, which can be obtained through the enumDevices interface. Device IDs are randomly generated, and in some cases, the ID of the same device may change. Therefore, we recommend calling the enumDevices interface every time you switch devices to get the device ID.
To protect user privacy, Chrome 81 and above, Safari, and Firefox browsers need to obtain media device permissions before they can get device IDs. You can create a temporary stream to capture audio and video to trigger media device permission requests and obtain complete device information. Use the following code to trigger microphone and camera permission requests.
const stream = zg.createStream();
zg.destroyStream(stream);-
Call enumDevices to get the device ID.
-
Call the following interfaces to switch devices in real-time.
- useVideoDevice: Switch camera
- useAudioDevice: Switch microphone
const deviceInfo = await zg.enumDevices();
// Switch camera
const cameras = deviceInfo.cameras;
const res = await zg.useVideoDevice(localStream, cameras[1].deviceID);
// Switch microphone
const microphones = deviceInfo.microphones;
const res = await zg.useAudioDevice(localStream, microphones[1].deviceID);Web Mobile Device Switching
The operation of switching audio input devices on mobile is the same as on desktop. For details, please refer to the previous section "Desktop Device Switching".
If you want to switch video input devices on mobile, such as switching from the rear camera to the front camera, you must first close the current video track before calling the device switching interface.
If you want to switch video input devices on mobile, such as switching from the rear camera to the front camera, you must first close the current video track before calling the useVideoDevice interface.
// Close the current video track
localStream.getVideoTracks().forEach(track => track.stop());
zg.useVideoDevices(localStream, deviceID);