简体   繁体   中英

Audio event listener on mobile doesn't work

I can't start playing an audio clip within eventlistener on a mobile device

<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.4.min.js'></script>
<script>
$(document).ready(function() {
    // Works with PC and Mobile
    $("#play").click(function() {
        var test = new Audio("http://www.w3schools.com/html/horse.ogg");
        test.volume = 1;
        test.play();
    });

    // Works with PC only
    $("#play2").click(function() {
        var test = new Audio("http://www.w3schools.com/html/horse.ogg");
        test.volume = 1;

        test.addEventListener('canplaythrough', function() {
            test.play(); // or this.play();
        });
    });
});
</script>
</head>
<body>
<button id='play'>Play</button>
<button id='play2'>Play 2</button>
</body>
</html>

The first button works on PC and Mobile but the second button with the event listener only works on PC. How can I get it to work on mobile too?

The event triggers, I can do alert(123); and it will execute, it just won't play the audio clip.

I found the answer.

You have to call:

test.play();
test.pause();

And after that you can control the audio element outside of the trigger event.

Mobile devices typically prevent playing of media unless directly called by an event (in this case, click ). This is to prevent usage of mobile data, but unfortunately limits what you can do with media.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM