Javascript 如何淡出JS创建的音频对象的音频?
当我试图运行这段代码时,我的编译器崩溃了。我已经在这里查看了这个问题的其他答案,但它们对我不起作用Javascript 如何淡出JS创建的音频对象的音频?,javascript,Javascript,当我试图运行这段代码时,我的编译器崩溃了。我已经在这里查看了这个问题的其他答案,但它们对我不起作用 let audio = { sound: { train: function() { this.train = new Audio( "train audio" ); this.train.play(); }, fadeOut: function(sound) { while (sound.volume > 0)
let audio = {
sound: {
train: function() {
this.train = new Audio(
"train audio"
);
this.train.play();
},
fadeOut: function(sound) {
while (sound.volume > 0) {
setTimeout(function() {
sound.volume - 0.1;
}, 1000);
}
}
fadeOut(audio.sound.train);
这实际上是一条评论,但由于声誉不佳,我无法发表评论 您的代码在音频末尾缺少}括号和分号
let audio = {
sound: {
train: function() {
this.train = new Audio(
"train audio"
);
this.train.play();
},
fadeOut: function(sound) {
while (sound.volume > 0) {
setTimeout(function() {
sound.volume - 0.1;
}, 1000);
}
}
//Here It was missing
};
//And why are you calling it here
fadeOut(audio.sound.train);
只回答调试部分 由于可以改变声音的内容只会在一秒钟内被调用,因此您的while循环将永远不会结束,在所有这些之前会使浏览器崩溃 回调可能会触发 相反,您可以将其重写为递归函数:
function fadeOut(sound) {
if( sound.volume > 0 ) { // only if we're not yet at 0
setTimeout(function() {
sound.volume -= 0.1;
fadeOut( sound ); // do it again after one second
}, 1000);
}
}
fadeOut( audio.sound.train );
但请注意,每秒减少0.1很难被称为淡出
也许您应该看看提供的Web音频API。必须将其更改为“sound.volume-=0.1”,但除此之外,这是可行的。