search

Home  >  Q&A  >  body text

How to automatically play sound on mouse enter event without clicking on document?

<p>I have the following HTML code: </p> <pre class="brush:php;toolbar:false;"><div id="word">word</div> <audio id="player"> <source id="source" src"sound.ogg" type="audio/ogg" /> </audio></pre> <p> and the following JavaScript/jQuery code: </p> <pre class="brush:php;toolbar:false;">$('#word').mouseenter(function() { var audio = $("#player")[0]; audio.load(); audio.play(); });</pre> <p>On my browser, this code only works if I <strong>click</strong> the document. Otherwise, it does not work and the following error appears in the JavaScript console: </p> <blockquote> <p>Uncaught (in promise) DOMException: Play method not allowed The user agent or platform in the current context, possibly Because the user denied permission. </p> </blockquote> <p>and the following warning: </p> <blockquote> <p>Allow autoplay only if user accepts, The user has interacted with the website or the media file has the volume set Return to zero. </p> </blockquote> <p>If I set the volume to zero, I get the following error: </p> <blockquote> <p>Uncaught (in promise) DOMException: Media retrieval process The user agent terminated the resource at the user's request. </p> </blockquote> <p>I tried it on both Chrome and Firefox. </p>
P粉744831602P粉744831602457 days ago682

reply all(1)I'll reply

  • P粉635509719

    P粉6355097192023-09-02 15:24:30

    <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>

    reply
    0
  • Cancelreply