<audio src="/music.mp3" autoplay></audio>Autoplay guide for media and Web Audio APIs / notebook
Autoplay guide for media and Web Audio APIs
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
audioElement.play();<audio id="musicplayer" autoplay>
<source src="/music/chapter1.mp3" />
</audio>if (navigator.getAutoplayPolicy("mediaelement") === "allowed") {
// The video element will autoplay with audio.
} else if (navigator.getAutoplayPolicy("mediaelement") === "allowed-muted") {
// Mute audio on video
video.muted = true;
} else if (navigator.getAutoplayPolicy("mediaelement") === "disallowed") {
// Set a default placeholder image.
video.poster = "https://example.com/poster_image_url";
}if (navigator.getAutoplayPolicy(video) === "allowed") {
// The video element will autoplay with audio.
} else if (navigator.getAutoplayPolicy(video) === "allowed-muted") {
// Mute audio on video
video.muted = true;
} else if (navigator.getAutoplayPolicy(video) === "disallowed") {
// Set a default placeholder image.
video.poster = "https://example.com/poster_image_url";
}<video src="my-video.mp4" id="video" autoplay></video>const video = document.getElementById("video");
video.addEventListener("play", handleFirstPlay);
let hasPlayed = false;
function handleFirstPlay(event) {
if (!hasPlayed) {
hasPlayed = true;
// Remove listener so this only gets called once.
const vid = event.target;
vid.removeEventListener("play", handleFirstPlay);
// Start whatever you need to do after first playback has started
}
}document.querySelector("video").play();let startPlayPromise = videoElem.play();
if (startPlayPromise !== undefined) {
startPlayPromise
.then(() => {
// Start whatever you need to do only after playback
// has begun.
})
.catch((error) => {
if (error.name === "NotAllowedError") {
showPlayButton(videoElem);
} else {
// Handle a load or playback error
}
});
}let playAttempt = setInterval(() => {
videoElem
.play()
.then(() => {
clearInterval(playAttempt);
})
.catch((error) => {
console.log("Unable to play the video, User has not interacted yet.");
});
}, 3000);<iframe src="mediaplayer.html" allow="autoplay"> </iframe><iframe src="mediaplayer.html" allow="autoplay; fullscreen"> </iframe><iframe
width="300"
height="200"
src="mediaplayer.html"
allow="autoplay 'src' https://example.media">
</iframe><iframe src="mediaplayer.html" allow="autoplay 'none'"> </iframe><video
src="/videos/awesomevid.webm"
controls
autoplay
playsinline
muted></video>