编辑*我这样做了:
if (vol > 0) {
vol -= 0.05;
document.getElementById("introMusic").volume = vol;
}
我收到了这个错误: Uncaught Error :IndexSizeError:DOM Exception 1 preGameContentObject.js:102
(匿名函数)。它会降低声音直到非常低,然后继续播放。
我从来没有用 javaScript 做过音频,我很菜鸟。这个问题几乎令人尴尬。我在这个网站上发现了这个很棒的功能,可以淡出我的乒乓球比赛的开场曲。
我用这个功能开始音乐:
setUpGame: function() {
this.setUpPaddles();
this.setUpBall("left");
preGameContent.getMouseHover();
preGameContent.drawButtons();
preGameContent.getMouseClick();
document.getElementById('introMusic').play();
},
这是最佳做法吗?有用。
我想知道如何将此功能应用于我的代码:
// 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);
我知道在哪里调用它,因为我有一个“如果点击玩游戏按钮 - 开始游戏”类型的功能,我会在那里弹出它。我在哪里将它引用到我的“introMusic”元素 ID?谢谢!
最佳答案
我改为这样做是因为它没有错误(需要稍微重构):
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;
});
为了停止我使用的音频
.pause();
并重置当前时间,因为 .stop();
不工作。有谁知道为什么?谢谢。
关于javascript - 如何将此代码应用于我的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17958610/