【发布时间】:2020-05-26 14:34:49
【问题描述】:
我使用以下代码向我的 HTML 文档添加声音。
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function(){
this.sound.play();
}
this.stop = function(){
this.sound.pause();
}
}
var bite = new sound("Bite+2.mp3");
var slurp = new sound("Slurp+4.mp3");
var hiss = new sound("snakehiss2.mp3");
var bg = new sound("gameSound.mp3");
现在,我想设置 'bg' 的音量并使其 loop = true
我想不出办法来做到这一点。请帮忙!!
另外,我在网上某处看到了代码,但我无法理解“this.sound”是如何工作的。请解释一下
编辑:
事实证明,我只需要执行 bg.sound.volume = 0.5 即可。同样,bg.sound.loop = true。
我也理解“this”的用法,但为什么需要“sound”?用 this.src 代替 this.sound.src 还不够吗?
【问题讨论】:
-
请限制自己每个问题回答一个问题。
this.sound是使用 JavaScript 的标准面向对象编程。见stackoverflow.com/questions/3127429/…。 -
要循环播放音频,请参阅Loop audio with JavaScript
-
@HereticMonkey 我确实阅读了这些问题,但我想知道如何用我实现它的方式来做到这一点。另外,我理解“this”,但我不明白在“this.sound”中将“sound”与“this”一起使用。我认为最好只问一个问题,而不是复制代码单独提出一个问题,但如果这里是这样做的,我会从下一次开始处理它。
-
this.sound指的是在sound的第一行创建的audio元素。设置this.src不会设置audio元素的src属性,从而违背了目的......您将包装函数/对象命名为与内部属性名称相同,这让您感到困惑。如果你称它为this.audio,并留下外部函数sound,也许更有意义?
标签: javascript html audio