billyblaze
billyblaze

Reputation: 69

jPlayer does not play first audio track after AJAX call on iOS/Android devices - works on Windows Phone

I'm having trouble getting jPlayer to play tracks on iOS and Android devices. It does work on Windows Phone. I need to download a tracklist as JSON over AJAX call. Doing so, causes Android Chrome to cancel the GET request to the set track.

This is making my head hurt since it works on desktop & windows phone :-)

Below is a small snippet of the code with similar idea.

$('.container').on('click', '.start', function(){
  $.ajax({
        url: "json/jsondata.json",
        dataType: "json",
        type: "GET",
        cache: true,
        context: document.body
  }).done(function(response){
    // while-loop through response
    // put track names in array etc...

    var mp3file = trackarray[0];
    App.$jmlPlayer.jPlayer("setMedia", {
        mp3: mp3file
    });

    // This doesn't work on iOS / Android
    $('.jmlPlayer').jPlayer("play");
  });
});

$('.container').on('click', '.next', function(){
  if(something){
    var mp3file = trackarray[nextIdx];
    App.$jmlPlayer.jPlayer("setMedia", {
        mp3: mp3file
    });
    // This does work on iOS / Android
    $('.jmlPlayer').jPlayer("play");     
  }
});

Upvotes: 2

Views: 1385

Answers (2)

actionshrimp
actionshrimp

Reputation: 5229

I believe this is due to both iOS and Android needing the initial play on an HTML5 audio element to be driven by a user click event - this is to prevent pages auto-playing audio.

Even though a user has initiated the play, as your actual call to play is inside the AJAX callback, the browser thinks this is not user-driven as the AJAX call could have been initiated by anything.

The workaround is, as you found, to trigger a play of some kind while inside the user click event context. Any additional calls to the player should then work from that point onwards as expected (wherever they originate from).

Alternatively setting async: false in your ajax call options seems to work as well, I guess this keeps the AJAX callback in the user click event context.

Upvotes: 3

billyblaze
billyblaze

Reputation: 69

Ok, after "few" hours of debugging this on iOS and Android devices, I found it to be easiest to play an empty .mp3 file on first user click/touch gesture. This way it works from there on out.

I have on idea why this works, but it just does.

Upvotes: 2

Related Questions