Manage Audio


This guide describes how to manage the audio, including how to start and stop audio, manage automatic playback of audio, mute and unmute, and switch the microphone and speaker.

Start and stop audio

Join users into session audio using the startAudio method. The SDK will automatically use the device’s microphone and speaker hardware.

const stream = client.getMediaStream();
stream.startAudio().then(() => console.log("join audio"));

To leave the session audio, use the stopAudio method:

stream.stopAudio().then(() => console.log("leave audio"));

Autoplay

Automatic playback of browser audio may be restricted by the browser. This may be due to a browser with autoplay restrictions. For example, if the user does not perform any interactive actions, such as clicking on the page, the web page cannot automatically play audio.

If the stream.startAudio method is called to play audio before the user interaction occurs, autoplay restrictions may prevent the user from hearing session audio. But if the user interacts with the page at any time, the SDK detects this behavior and attempts to resume audio playback for the session.

We recommend that you ensure a user has interacted with the page before calling stream.startAudio. If your user experience can’t guarantee this, you may want to use the auto-play-audio-failed callback to prompt the user to interact with the page when the playback fails:

client.on("auto-play-audio-failed", () => {
  console.log("auto play failed, waiting user interaction");
});

Mute and unmute

A participant can mute or unmute their own audio during a session. A host or manager can also mute or unmute participants.

Use the stream.mute or stream.unmute methods with a required userId:

// host side
await stream.unmuteAudio(userId);

// participant side
client.on('unmute-audio-consent',(payload)=>{
   console.log('Host ask me to unmute');
);
Note

The host can not unmute the participant’s audio directly, instead, the participant will receive an unmute audio consent request that they can choose to accept or reject.

Switch the microphone and speaker

To switch the current microphone, use the stream.switchMicrophone method with a microphoneId. To switch the current speaker, use the stream.switchSpeaker method with a speakerId:

// switch microphone
stream.switchMicrophone(microphoneId);
// switch speaker
stream.switchSpeaker(speakerId);

Use the device-change event to detect if a microphone or speaker has been plugged in or unplugged:

client.on('device-change',()=>{
  // get the latest devices
  const microphones = stream.getMicList();
  const speakers = stream.getSpeakerList();
});