我有一些元素可以在单击或单击鼠标时发出声音。我想在用户单击按钮时使这些声音效果静音,而在再次单击按钮时取消静音。
示例:https://pebble-kiss.glitch.me/
到目前为止,我只能使背景音频静音,而不能使鼠标进入并单击音频。有没有办法做到这一点,还是我必须管理js中的所有声音?
<a-plane id="audioButton" color="#FF0000" width=".5" height=".5" position="-2 2 0" audiohandler></a-plane>
<a-box class="sound" sound="src: #audio; autoplay: true; loop: true; volume: 15;" position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" shadow></a-box>
<a-box class="sound" position="1 0.5 -3" rotation="0 45 0" color="#000000" sound="on: mouseenter; src: #mouseenter;"></a-box>
<a-box class="sound" position="2.5 0.5 -3" rotation="0 45 0" color="#00FF00" sound="on: click; src: #click;"></a-box>
AFRAME.registerComponent('audiohandler', {
init:function() {
var playing = true;
var audio = document.querySelectorAll(".sound");
this.el.addEventListener('click', function() {
console.log("click");
if(!playing) {
audio.forEach(function(playAudio) {
playAudio.components.sound.playSound();
});
} else {
audio.forEach(function(pauseAudio) {
pauseAudio.components.sound.stopSound();
});
}
playing = !playing;
});
}
});
答案 0 :(得分:2)
您的组件正在停止声音和播放声音之间切换。如果您想将它们静音,则只需翻转音量即可。
由于每个元素的卷数不同,因此应存储它们。 在尝试获取卷之前,请确保已加载元素!
要静音时,只需遍历元素,然后在0(静音)和存储的值之间切换:
AFRAME.registerComponent('muter', {
init:function() {
var audio = document.querySelectorAll(".sound");
// lets store volume levels for later use
var volLevels = {}
audio.forEach(function(el, index) {
el.addEventListener('loaded', e=> {
volLevels[index] = el.getAttribute('sound').volume
})
})
var muted = false
// when clicked - switch the volume
this.el.addEventListener('click', function() {
audio.forEach(function(playAudio, index) {
let volume = muted ? volLevels[index] : 0
playAudio.setAttribute('sound', 'volume', volume)
});
muted = !muted
});
}
});
小故障here