Page 1 of 1

Playing audio on page load doesn't work when returning to page

Posted: Wed Feb 03, 2016 9:03 am
by billyboy5000

I am using this method to load audio onto the page: https://blog.appery.io/2015/10/how-to...

and then using on page show event to trigger javascript and play the audio like so...

PlayTrack("sounds/theme.mp3");

This works and when i first open the app the audio is playing but if i navigate to another page and then come back to the first page the audio does not play on page load again - i see in the source the audio is not loaded. I am guessing that the js file method of loading the audio does not happen because the dom is not refreshed. So that js file needs to be modified not to use onload... wish i knew how to do that.. the contents of the js file are below...

var onLoad = function() {
var audioText = 'source src="https://sounds/theme.mp3"source/source/source';
var audio = jQuery(audioText);
jQuery("body").append(audio);
console.log("load");
};
jQuery(window).bind("load", onLoad);

// Play function
function PlayTrack(src) {
var au = jQuery("#yourAudio");
au.attr("src", src);
if (au[0] && au[0].play) au[0].play();
}

// Stop playing function
function StopPlayTrack() {
var au = jQuery("#yourAudio");
if (au[0] && au[0].play) au[0].pause();
}


Playing audio on page load doesn't work when returning to page

Posted: Wed Feb 03, 2016 1:38 pm
by Evgene Karachevtsev

Hello,

Please try your code on Page Show event.


Playing audio on page load doesn't work when returning to page

Posted: Wed Feb 03, 2016 11:15 pm
by billyboy5000

Hi if you read my post it says that I did try that.
The code to play the sound is on a page show event.
The js code in the end of my post is in a js file.


Playing audio on page load doesn't work when returning to page

Posted: Thu Feb 04, 2016 7:02 am
by billyboy5000

I have now figured this out. What i had to do was leave this code in the sounds.js file

// Play function
function PlayTrack(src) {
var au = jQuery("#yourAudio");
au.attr("src", src);
if (au[0] && au[0].play) au[0].play();
}

// Stop playing function
function StopPlayTrack() {
var au = jQuery("#yourAudio");
if (au[0] && au[0].play) au[0].pause();
}

Then i moved this code into the page show event on each page

Code: Select all

 var audioText = 'source src="https://sounds/theme.mp3"source/source/source'; 
 var audio = jQuery(audioText); 
 jQuery("body").append(audio); 
 console.log("loaded audio"); 
  • without much experience in jquery and javascript it was pretty difficult to fix for me and it took hours of playing around with code.