Javascript A帧静音所有声音,包括按钮上的声音组件单击

Javascript A帧静音所有声音,包括按钮上的声音组件单击,javascript,aframe,Javascript,Aframe,我有一些元素可以在点击或鼠标时播放声音。我想在用户单击按钮时使这些声音效果静音,在再次单击按钮时取消静音 例如: 到目前为止,我只能够静音的背景音频,但没有鼠标点击音频。有没有办法做到这一点,或者我必须管理js中的所有声音 <a-plane id="audioButton" color="#FF0000" width=".5" height=".5" position="-2 2 0" audiohandler></a-plane> <a-box class=

我有一些元素可以在点击或鼠标时播放声音。我想在用户单击按钮时使这些声音效果静音,在再次单击按钮时取消静音

例如:

到目前为止,我只能够静音的背景音频,但没有鼠标点击音频。有没有办法做到这一点,或者我必须管理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;
      });
    }
  });

AFRAME.registerComponent('audiohandler'{
init:function(){
var=true;
var audio=document.queryselectoral(“.sound”);
this.el.addEventListener('click',function(){
控制台日志(“单击”);
如果(!玩){
音频.forEach(功能(播放音频){
playAudio.components.sound.playSound();
});
}否则{
音频.forEach(功能(pauseAudio){
pauseAudio.components.sound.stopSound();
});
}
玩=!玩;
});
}
});

您的组件正在停止和播放声音之间切换。如果要使其静音,只需翻转音量即可

因为每个元素有不同的卷,所以应该存储它们。 在尝试抓取卷之前,请确保已加载元素

如果要禁用,只需迭代元素,并在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
  });
 }
});

小故障

谢谢!这对我来说很有意义,但我似乎无法让它发挥作用。。。这里有一个新代码的更新故障:@L.Maher哦,我复制粘贴太多了。应使用
setAttribute()
切换音量。我已经修改了我的anwser+故障