To prevent the webpage from playing sound without permission, most web browsers restrict the autoplay function: Autoplay with sound is blocked unless the user has interacted with the webpage (by clicking, tapping, or other gesture). This restriction policy is intended to improve the user experience, because autoplay with sound may be against the users' deliberate intention.
On most web browsers, inaudible media are not affected by autoplay blocking. However, on iOS Safari with low power mode enabled, or on other iOS in-app browsers that implement a custom autoplay policy, such as the WeChat browser, the autoplay of inaudible media is blocked.
When it comes to the Agora Web SDK, the autoplay blocking policy may cause playback failure so long as you call the play
method to play an audio or video track before any user interaction.
This document describes how to get around the autoplay blocking policy in the following methods:
Listen for the onAutoplayFailed
callback. When the autoplay of an audio track or a video track fails, prompt the user to interact with the webpage to resume the playback.
The following code demonstrates how to display a button for the user to click when autoplay fails.
play
for multiple audio and video tracks in a short time, the SDK only triggers onAutoplayFailed
once before a user gesture that removes the autoplay blocking.AgoraRTC.onAutoplayFailed = () => {
const btn = document.createElement("button");
btn.innerText = "Click me to resume the audio/video playback";
btn.onClick = () => {
btn.remove();
};
document.body.append(btn);
}
If the user has interacted with the webpage before play
is called, autoplay with sound is allowed.
This method can work around almost all the autoplay blocks for the browsers on your PC but does not apply to iOS Safari or WebView. See the following section for our suggested workaround for iOS Safari and WebView.
iOS Safari or WebView has a stricter autoplay policy. It only allows playback with sound that is triggered by user intervention and does not remove the autoplay block after a user intervention.
If your app works on iOS Safari or WebView, Agora recommends handling autoplay in the following way:
// HTML
<div id="user1-audio">Muted</div>
// JavaScript
document.getElementById("user1-audio").onClick = (e) => {
if (user1.audioTrack.isPlaying) {
user1.audioTrack.stop();
e.target.innerHTML = "Muted";
return;
}
user1.audioTrack.play();
e.target.innerHTML = "Playing";
}