In my app, I would like to play a .mp3
and then move to another page afterwards.
Currently I have:
// Ajax Success function
$.playSound('../static/sounds/cash-register');
window.location.replace("next_page");
// Play sound function
(function($){
$.extend({
playSound: function(){
return $("<embed src='"+arguments[0]+".mp3' hidden='true' autostart='true' loop='false' class='playSound'>" + "<audio autoplay='autoplay' style='display:none;' controls='controls'><source src='"+arguments[0]+".mp3' /><source src='"+arguments[0]+".ogg' /></audio>").appendTo('body');
}
});
})(jQuery);
This works fine when I don't move to another page immediately afterwards. However with my current code, the .mp3
doesn't play and I am simply moved to the next page.
Would anyone have any idea as to how I might rectify this?
You need to start the mp3 playing but wait to navigate to the next page until the mp3 has finished. You can do this by listening to the media events available from your audio element.
Please take a look at this link for more information on the media events available to you: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
I modified your code to implement this event. Please take a look at the source below.
// Ajax Success function
$.playSound('../static/sounds/cash-register', 'next_page');
// Play sound function
(function($){
$.extend({
playSound: function(){
var $ele = $("<embed src='"+arguments[0]+".mp3' hidden='true' autostart='true' loop='false' class='playSound'>" + "<audio autoplay='autoplay' style='display:none;' controls='controls'><source src='"+arguments[0]+".mp3' /><source src='"+arguments[0]+".ogg' /></audio>").appendTo('body');
$ele.on('ended', function() {
window.location.replace(arguments[1]);
});
}
});
})(jQuery);