I am creating a simple background music which has only one button to play and stop the music. But I would like to add fade to it. But does not work.
My code:
var beepTwo = $("#musicBeat")[0];
beepTwo.play();
$("#dan").click(function() {
if (beepTwo.paused == false) {
beepTwo.pause();
} else {
beepTwo.play();
}
});
$beepTwo.animate({volume: newVolume}, 1000);
JSFiddle
I found $audio.animate({volume: newVolume}, 1000);
in another post but does not work for me or maybe I didnt use it correctly. Anyway I want to have a fade in and fade out when the button is pressed. So it plays with fadeIn and stops with fadeOut. How can I do that?
I am creating a simple background music which has only one button to play and stop the music. But I would like to add fade to it. But does not work.
My code:
var beepTwo = $("#musicBeat")[0];
beepTwo.play();
$("#dan").click(function() {
if (beepTwo.paused == false) {
beepTwo.pause();
} else {
beepTwo.play();
}
});
$beepTwo.animate({volume: newVolume}, 1000);
JSFiddle
I found $audio.animate({volume: newVolume}, 1000);
in another post but does not work for me or maybe I didnt use it correctly. Anyway I want to have a fade in and fade out when the button is pressed. So it plays with fadeIn and stops with fadeOut. How can I do that?
- 1 you have to set a value in newVolume, and the logic is incorrect. – clouddreams Commented Feb 6, 2014 at 19:00
1 Answer
Reset to default 5You have to watch out for the difference between the HTMLAudioElement ($('#musicBeat')[0]
) and the jQuery Object ($('#musicBeat')
).
play
is a method of the HTMLAudioElement, so you'll have to access it over that (as you did), but .animate
is a jQuery method and can only be called on a jQuery object.
And you have to specify newVolume (can't leave it empty).
var beepTwo = $("#musicBeat");
beepTwo[0].play();
$("#dan").click(function() {
if (beepTwo[0].paused == false) {
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
beepTwo[0].pause();
});
} else {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
}
});