简体   繁体   中英

Playing Random Audio Tracks on mobile browsers

Objective:

User taps a button.

A random audio track is selected (among 3 tracks) and plays in the background.

Problem: The track plays on desktop Chrome and Firefox, but does not play on Mobile Chrome.

JS:

    function play() {
        var a = Math.random() * 3;
        a = Math.floor(a);

        if (a == 0) {
            document.getElementById('soundtrack').innerHTML = "<audio id='background_audio1' loop autoplay><source src='0.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
        }
        if (a == 1) {
            document.getElementById('soundtrack').innerHTML = "<audio id='background_audio1' loop autoplay><source src='1.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
        }
        if (a == 2) {
            document.getElementById('soundtrack').innerHTML = "<audio id='background_audio1' loop autoplay><source src='2.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
        }
    }

HTML:

    <a class="button" onclick="play()"><img src="image.png"/></a>

    <div id="soundtrack"></div>

How do I make this play on Mobile browsers? This is event driven (tap button) and not auto-play. It should play but does not.

Actually it appears that it is autoplay, because you're not playing the file on event (tap), you're simply loading new HTML code which then requests for an autoplay.

It might work if you request the play action in javascript immediately after replacing the HTML: document.getElementById('background_audio1').play();

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