word and the " /> word and the " /> word and the "/>

How can I play a sound on mouseenter event, without clicking on the document first?

283 Views Asked by At

I have the following HTML code:

<div id="word">word</div>

<audio id="player">
    <source id="source" src"sound.ogg" type="audio/ogg" />
</audio>

and the following JavaScript/jQuery code:

$('#word').mouseenter(function()
{
    var audio = $("#player")[0];
    audio.load();
    audio.play();
});

On my browser this code only works, if I click on the document first. Otherwise it does not work and in the JavaScript console I get this error:

Uncaught (in promise) DOMException: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

and this warning:

Automatic playback is permitted only when accepted by the user, the user has interacted with the site or the media file has the volume set to zero.

If I set the volume to zero, I get the following error:

Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request.

I tried both on Chrome and Firefox.

1

There are 1 best solutions below

4
Ashwini shinde On
<div id="word" style="font-size: 30px; margin-bottom: 200px; ">word</div>
    
<audio id="player" controls preload="auto">
     <source src="audio/beep.mp3" controls></source>
     <source src="audio/beep.ogg" controls></source> 
</audio>
 
<script>
    var player = $("#player")[0];
        $("#word").mouseenter(function() {              
        player.play();
    }); 
</script>