The Agora Web SDK identifies media input devices by the device ID (deviceId). Each device has a unique device ID that you can get by getDevices. The device ID is randomly generated, and may change for the same device, so Agora recommends calling getDevices every time before switching the device.

On Chrome 81 or later, Safari, and Firefox, device IDs are only available after the user has granted permissions to use the media device. See Why can't I get device ID on Chrome 81?

For the Agora Web SDK v2.5.0 or later

  1. Call getDevices to enumerate available devices and get the device IDs.
  2. Call switchDevice after getting the device ID.
switchDevice does not work on Firefox, and cannot switch audio input devices on Safari 11 or earlier. See the API Reference for other limitations.

Switch cameras on mobile devices

To switch cameras on mobile devices, for example, switching between the rear camera and the front camera, you need to stop the current video track before calling switchDevice.

switchBtn.onclick=()=>{
  localStream.getVideoTrack().stop();
  localStream.switchDevice("video",devices.value);
};

For versions earlier than v2.5.0

Set the microphoneId and cameraId parameters in the createStream method to switch the microphone and camera.

  1. Call close to close the local stream.
  2. Call getDevices to enumerate available devices and get the device IDs.
  3. Call createStream and fill the microphoneId or cameraId parameter with the device ID.

To use the first input device by default, set cameraId and microphoneId as "" in createStream.