JiminP
JiminP

Reputation: 2142

Play music (in iPhone) just after the page is loaded (using HTML5/JS)

I found that:

<!DOCTYPE html>
<html>
    <head>
    <script src='jQuery.js'></script>
        <script>
                $(document).ready(function(){
                    document.getElementById("asdf").play();
                });
        </script>
    </head>
    <body>
        <audio src='music.m4a' id='asdf'></audio>
    </body>
</html>

or

<!DOCTYPE html>
<html>
    <head>
        <script>
            setTimeout('document.getElementById("asdf").play();',10000);
        </script>
    </head>
    <body>
        <audio src='music.m4a' id='asdf'></audio>
    </body>
</html>

will not play the music on iPhone (of course above two works in normal computer), but writing

<!DOCTYPE html>
<html>
    <body>
        <audio src='music.m4a' id='asdf'></audio>
        <a href='javascript:document.getElementById("asdf").play()'>dd</a>
    </body>
</html>

and click on 'dd' will play the music.

My question is : how to automatically play the music right after the page is loaded (and 'ready' to play the music) in iPhone?

PS : I added setInterval('if($("#asdf").attr("readyState")) console.log(1);'); for check whether the sound is loaded, and I found that readyState is changed right after I pressed 'dd'.

Upvotes: 2

Views: 1959

Answers (4)

Ian Devlin
Ian Devlin

Reputation: 18880

Autoplay of video/audio files on iPhones and iPads is not allowed. This is a decision taken by Apple.

Upvotes: 3

alex
alex

Reputation: 490433

You would need to wait until the audio has loaded enough to begin playing it.

Documentation.

Upvotes: 0

tildy
tildy

Reputation: 1009

Try this

 <audio src='music.m4a' autoplay="autoplay" id='asdf'></audio>

Upvotes: 1

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

HTML audio tag has a autoplay attribute which specifies whether or not to start playing the audio as soon as the object has loaded.

Check here

Upvotes: 0

Related Questions