I am building a website with a question at the beginning, if the user allows background music. After he clicked the "ok" button an audiocontext is created and the music starts playing.
When the user is changing the page of the website, I want to autoplay another song without asking the user on every page.
This seems to work on Chrome and Edge, but on Safari and Firefox it doesnt.
Here is my testcode.
// Did the user allow autoplay before?
const autoplay = window.sessionStorage.getItem("autoplay") || "0";
// Run this function on page load when the user allowed autoplay
const play = (() => {
// Create audioContext
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Load audio file
fetch("counting.mp3")
.then((response) => response.arrayBuffer())
.then((buffer) => audioContext.decodeAudioData(buffer))
.then((decodedData) => {
// Create bufferSource
const bufferSource = audioContext.createBufferSource();
bufferSource.connect(audioContext.destination);
bufferSource.loop = true;
bufferSource.buffer = decodedData;
// Resume audioContext in case its not running for any reson
audioContext.resume().then(() => {
// Play audio file
bufferSource.start(0);
});
});
});
// Start playing when autoplay was enabled
if (autoplay === "1") {
play();
}
You can test it here: