【问题标题】:A-Frame mute all sound including sound component on button clickA-Frame 静音所有声音,包括按钮单击时的声音组件
【发布时间】:2023-04-01 21:32:01
【问题描述】:

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

示例: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;
      });
    }
  });

【问题讨论】:

    标签: javascript aframe


    【解决方案1】:

    您的组件正在停止和播放声音之间切换。如果您想将它们静音,您只需调低音量即可。

    由于每个元素都有不同的卷,因此您应该存储它们。 在尝试抓取卷之前确保已加载元素!

    当你想静音时,只需遍历元素,并在 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

    【讨论】:

    • 谢谢!这对我来说很有意义,但我似乎无法让它工作......这是新代码的更新故障:glitch.com/edit/#!/cyan-jade?path=index.html:18:3
    • @L.Maher 哦,我复制粘贴太多了。音量应使用setAttribute() 切换。我修改了我的 anwser + 故障
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    相关资源
    最近更新 更多