edit* I did this:
if (vol > 0) {
vol -= 0.05;
document.getElementById("introMusic").volume = vol;
}
I got this error: Uncaught Error: IndexSizeError: DOM Exception 1 preGameContentObject.js:102 (anonymous function). It decreases in sound untill it is very low, then keeps playing.
i've never done audio with javaScript and am very noob. This question is almost embarrassing. I found this great function on this website to fade out my opening song for my pong game.
I start the music with this function:
setUpGame: function() {
this.setUpPaddles();
this.setUpBall("left");
preGameContent.getMouseHover();
preGameContent.drawButtons();
preGameContent.getMouseClick();
document.getElementById('introMusic').play();
},
Is that best practice? It works.
I would like to know how to apply this function to my code:
// Initial volume of 0.20
// Make sure it's a multiple of 0.05
var vol = 0.20;
var interval = 200; // 200ms interval
var fadeout = setInterval(
function() {
// Reduce volume by 0.05 as long as it is above 0
// This works as long as you start with a multiple of 0.05!
if (vol > 0) {
vol -= 0.05;
audio.setVolume(vol);
}
else {
// Stop the setInterval when 0 is reached
clearInterval(fadeout);
}
}, interval);
I know where to call it, because i have an "if play game button clicked - start game" type of function that works, and i would pop it in there. Where do i reference it to my "introMusic" element ID? Thanks!
I went for this instead because it had no error (it needs to be refactored slightly):
function fadeVolume(volume, callback)
{
var factor = 0.02,
speed = 50;
if (volume > factor)
{
setTimeout(function(){
fadeVolume((document.getElementById("introMusic").volume -= factor), callback);
}, speed);
} else {
(typeof(callback) !== 'function') || callback();
}
}
fadeVolume(document.getElementById("introMusic").volume, function(){
console.log('fade complete');
document.getElementById("introMusic").pause();
document.getElementById("introMusic").currentTime = 0;
});
To stop the audio i used .pause();
and reset the current time, because .stop();
did not work. Does anyone know why? Thanks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.