I am using a ringtone array. When a user sets an alarm. Meanwhile, its alarm content (ringtone, hour, minute, alarm name, etc.) is stored in its browser's local storage.
Content (ringtone, hour, minute, alarm name, etc.) is retrieved from local storage.
The path to the desired ringtone is searched for by the ringtone name.
The path to the desired ringtone is added to the new Audio() function.
const ringsobj = {
battle: "./rings/gun-battle-long-34065.mp3",
beep: "./rings/alarm-clock-beep-close-perspective-7092.mp3",
short: "./rings/alarm-clock-short-6402.mp3",
}
for (const localnum of localstorage) {
for (const ring in ringsobj) {
if (ring === localnum.ringtones) {
yourringtone = new Audio(ringsobj[ring]);
ringtone = true;
}
}
}
A function is created to play the ringtone.
function playRingtones() {
console.log("Alarm data:", yourringtone);
yourringtone.play();
}
Case 1: This function is executed when the alarm time is reached.
setTimeout(() => {
console.log("Run the timeout!");
playRingtones();
}, 5000);
Case 2: This function is executed when the alarm time is reached.
setTimeout(() => {
console.log("Run the timeout!");
clocksection.click();
playRingtones();
}, 5000);
clocksection.addEventListener("click", () => {
console.log("Click on Clocksection!");
});
In both these cases this error is coming. DOMException: play() failed because the user didn't interact with the document first.
When moving from other page to this page then alarm is going on. But if the user has to interact with the document just before the alarm, then what is the use of the alarm.
This function is used to solve this problem.
playRingtones();
But it's not returning the expected result.
Browsers have restrictions on auto-playing audio or video content as it can create an unintended experience for the user. Browsers require some kind of user interaction.
Also, you must set the audio to be muted by default if it doesn't gets any action from user.
An alternative but not-so-brilliant way could be to use Notifications Web API which will trigger a browser notification on a certain event. It might not be what you are looking for but this is the best we can do (unfortunately).