Vishnu Kerasiya
Vishnu Kerasiya

Reputation: 11

Video or Audio autoplay play with sound without user interaction

I have a ticket booking website. When a ticket is ready to be served, a modal should open, and a sound should play along with the ticket information. I want the sound to play without requiring user interaction to provide a better user experience.

The website has two pages: one is the login page and the other is the ticket serving list. When a user enters the website step by step, first logging in and then navigating to the ticket serving page, the user interaction condition is fulfilled, and the audio plays with sound. However, there is one caveat: when I'm on the ticket serving page and refresh, the user interaction memory is reset, so the user has to click somewhere again. I want to play the audio with sound without requiring user interaction to improve the website experience.

According to the Chrome autoplay documentation, it is mentioned that top frames can delegate autoplay permissions to their iframes to allow autoplay with sound.

Does anyone have an idea of how to implement this?

I tried iframe delegation but did not get success till now.

Upvotes: 0

Views: 71

Answers (1)

Super Zombi
Super Zombi

Reputation: 26

Browser policy prohibits autoplay to prevent abuse. At least minimal user interaction with the page must occur for the sound to play. Here's what you can do:

function initUserInterac() {
    const handler = function() {
        window.localStorage.setItem('user_interacted', 'true');
        document.body.removeEventListener("click", handler, true);
    }
    document.body.addEventListener("click", handler, true);
}

function hasUserInteracted() {
    return window.localStorage.getItem('user_interacted') === 'true';
}

function main() {
    // ...
    if (hasUserInteracted()) {
        playSound();
    }
}

Upvotes: 0

Related Questions