2

I have a page for which i need to play a sound (audio tag or js Audio object) at a specific instance. The audio file location is not in my local webserver, it's at another server accessed like 'https://site.com/folder/file.wav'

I need to access and load this file at page load and need to play it without having a delay. Adding my current code below

<script> 
var player = new Audio();

$(document).ready(function () {
player.src = 'https://site.com/folder/file.wav';
});

function play()
{
player.play();
}
</script>

Problem i'm facing now is, if i'm running it from a computer with WIFI, it plays ontime; but if i run that from my android mobile it plays after 3-5 seconds.

Please advise.

DieOnTime
  • 493
  • 1
  • 5
  • 8

1 Answers1

0

I think you need to postpone displaying the page until enough of the audio has loaded to allow it to play through (see this answer).

Something like the following should be enough to get you started:

// Hide the page until the audio has loaded. 
// You might want to display some kind of preloader graphic 
// while the user waits.
var $body = $('body').css('display', 'none');

$(document).ready(function () {

    var player = new Audio();

    // canplaythrough event is fired when enough of the audio has downloaded
    // to play it through at the current download rate
    player.addEventListener('canplaythrough', audioLoadedHandler);


    function audioLoadedHandler(e) {
        // Audio has loaded, show the page
        $body.css('display', 'block');
        // And start the audio
        player.play();
    }       

    player.src = 'https://site.com/folder/file.wav';
});
Community
  • 1
  • 1
net.uk.sweet
  • 12,444
  • 2
  • 24
  • 42
  • Just a query, when will the audio object starts downloading the file? When we give the URL or some other event? In my case i need the file to be loaded but, play later – DieOnTime May 21 '14 at 09:28
  • It will start loading when you set the src. It will start playing when you call play on your audio element which you can do reliably anytime after the canplaythrough event has fired. – net.uk.sweet May 21 '14 at 09:34