The Agora Web SDK provides APIs for managing media devices, such as dynamically switching the audio and video input devices during a call and dealing with the hot plugging of audio and video input devices.
When calling AgoraRTC.createCameraVideoTrack
to create a local video track and calling AgoraRTC.createMicrophoneAudioTrack
to create a local audio track, you can set cameraId
and microphoneId
to specify the devices. After creating the audio and video tracks, you can call CameraVideoTrack.setDevice
and MicrophoneAudioTrack.setDevice
to dynamically switch the media devices.
The videoTrack
object in the following sample code is created by calling AgoraRTC.createCameraVideoTrack
.
// Switch the camera.
videoTrack.setDevice("<NEW_DEVICE_ID>").then(() => {
console.log("set device success");
}).catch(e => {
console.log("set device error", e);
});
You can call
setDevice
before or after publishing the video track. However, this method may not take effect on some mobile devices.
The Agora Web SDK provides the AgoraRTC.onMicrophoneChanged
and AgoraRTC.onCameraChanged
methods to listen for and identify the state of an audio or video input device. If you want to use a new device when it is plugged in, you need to listen for the AgoraRTC.onMicrophoneChanged
or AgoraRTC.onCameraChanged
callback and call the MicrophoneAudioTrack.setDevice
or CameraVideoTrack.setDevice
method to switch the audio and video input devices.
AgoraRTC.onMicrophoneChanged = async (changedDevice) => {
// When plugging in a device, switch to a device that is newly plugged in.
if (changedDevice.state === "ACTIVE") {
microphoneTrack.setDevice(changedDevice.device.deviceId);
// Switch to an existing device when the current device is unplugged.
} else if (changedDevice.device.label === microphoneTrack.getTrackLabel()) {
const oldMicrophones = await AgoraRTC.getMicrophones();
oldMicrophones[0] && microphoneTrack.setDevice(oldMicrophones[0].deviceId);
}
}
AgoraRTC.onCameraChanged = async (changedDevice) => {
// When plugging in a device, switch to a device that is newly plugged in.
if (changedDevice.state === "ACTIVE") {
cameraTrack.setDevice(changedDevice.device.deviceId);
// Switch to an existing device when the current device is unplugged.
} else if (changedDevice.device.label === cameraTrack.getTrackLabel()) {
const oldCameras = await AgoraRTC.getCameras();
oldCameras[0] && cameraTrack.setDevice(oldCameras[0].deviceId);
}
}