javascript- How to play an audio file 5 seconds after the loading of a webpage?

2.6k views Asked by At

I want to play an audio file 5 seconds after the loading of a webpage. I wrote the following code, but it does not work. Can someone teach me how to play an audio file 5 seconds after the loading of a webpage? I appreciate your great help. Thanks.

The following code works on a IE. I majorly want to make it work for FIREFOX-3.0. In firefox, I got an error saying that 'document.getElementById('audiotag1').play' is not a function. How can I make it work for firefox?

            <html>
        <head>
        <script type="text/javascript">
        function doTimer(length, resolution, oninstance, oncomplete)
        {
            var steps = (length / 100) * (resolution / 10),
                speed = length / steps,
                count = 0,
                start = new Date().getTime();
            function instance()
            {
                if(count++ == steps)
                {
                    oncomplete(steps, count);
                }
                else
                {
                    oninstance(steps, count);
                    var diff = (new Date().getTime() - start) - (count * speed);
                    window.setTimeout(instance, (speed - diff));
                }
            }
            window.setTimeout(instance, speed);
            }


            doTimer(5000, 20, function(steps)
        {   
        },
        function() {
                document.getElementById('audiotag1').play();
            }
        );

            </script>

            <script type="text/javascript">
            function play_single_sound() {
                document.getElementById('audiotag1').play();
            }
        </script>
        </head>
        <body>
        Timer out

        <audio id="audiotag1" src="https://www.dropbox.com/s/0kf457qwu6zh5q4/warning_alarm.mp3" preload="auto"></audio>
        <a href="javascript:play_single_sound();">warning_alarm</a>

        </body>
        </html>
2

There are 2 answers

0
Michael Geary On

I don't know why that doTimer() function is doing so much work, but you could replace the whole thing (and the call to it) with:

<script>
    setTimeout( function() {
        document.getElementById('audiotag1').play();
    }, 5000 );
</script>

That's really all you need.

(I'm assuming of course that the document.getElementById('audiotag1').play(); code itself works.)

0
jared On

this works:

        <script type="text/javascript">
        function play_single_sound() {
            console.log("ok");
            document.getElementById('audiotag1').play();
        }
        setTimeout(play_single_sound, 2000);
    </script>
    </head>
    <body>
    Timer out

    <audio id="audiotag1" src="warning_alarm.mp3" ></audio>
    <a href="javascript:play_single_sound();">warning_alarm</a>

    </body>
    </html>

but i've made the mp3 local to the page, taken out the preload.