Play a sound effect when a page loads

Viewed 53

I'm trying to play a sound effect when a page loads using Svelte. I tried onMount, but there is no sound.

Here is what I have so far:

<script lang="ts">

    import { onMount } from 'svelte';


    let celebration: HTMLAudioElement;

    onMount(() => {
        celebration.play();

        setTimeout(() => {
            celebration.pause();
            celebration.currentTime = 0;
        }, 1000);
    });
</script>

<audio
    src='https://sveltejs.github.io/assets/music/strauss.mp3'
    preload="auto"
    bind:this={celebration}
    controls
>
    <track kind="captions" />
</audio>
1 Answers

The problem is with the autoplay policies in web browsers. In short, you can't play a sound when a page loads because (as the error message says) the user has to interact with the page first.

You can look at the Autoplay policy in Chrome article which says:

Autoplay with sound is allowed if:

  • The user has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
  • The user has added the site to their home screen on mobile or installed the PWA on desktop."

So if you don't meet that criteria, you can't play audio. But you should read the article for more info, to understand the reasoning and maybe to find a workaround or an alternative.

Some other related links:

Related