Reputation: 28853
I have built a simple tour on my website that will be coded using HTML5 animation. It will use sound from the HTML5 audio tag and the tour will be loaded in using jquery.
When the tour is loaded it will start playing the audio and the user can mute the sound by toggling a link. And if they close the tour then the audio is reset!
I have parts of this working but don't seem to be able to properly toggle the music on and off and then stop it completely if they close the tour. Can anyone help?
var sound;
$(document).ready(function ()
{
sound = $('#soundTour');
$('.sound a').click(function()
{
$(this).parents('div').toggleClass('mute');
if (sound.paused)
{
sound.play();
}
else
{
sound.pause();
}
});
$('.showTour').click(function()
{
$('body').addClass('theatre'); $('#tour').fadeIn('slow', function() { });
sound.trigger('play');
});
$('#tour').find('.tourClose').click(function()
{
$('body').removeClass('theatre'); $('#tour').fadeOut('slow', function() { });
sound.currentTime=0;
sound.pause();
});
});
Upvotes: 2
Views: 4708
Reputation: 318342
You are using jQuery's trigger() to trigger events that are not defined in the posted code, as such it is difficult to really say what 'stop' is, but as a general rule HTML5 Audio does not have a stop() function, only play() and pause(), to reset the audio just define the source again or set the .currenttime to zero, like so:
var audioElm = document.getElementById('soundTour');
audioElm.src = 'myaudio.mp3';
audioElm.load();
or
var audioElm = document.getElementById('soundTour');
audioElm.currentTime=0;
audioElm.pause();
Setting currentTime only rewinds the audio to the beginning, and does not really stop it.
Here's a fiddle to show one way of doing it. It uses a mp3 file so your browser must support that format: http://jsfiddle.net/adeneo/n6Bar/1/
Upvotes: 5