javascript - A-Frame 将所有声音静音,包括单击按钮时的声音组件

标签 javascript aframe

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

示例: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(静音)和存储值之间切换:

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

关于javascript - A-Frame 将所有声音静音,包括单击按钮时的声音组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285828/

相关文章:

javascript - 如何使用jQuery从 "div"标签的css中获取值?

javascript - 如何找到表单/网页上按钮后面的来源或链接?

javascript - 如何使用 Javascript 键盘事件触发 CSS Sprite 动画

javascript - 如何在javascript中检测字符串中的空格

javascript - 排序对象然后进一步子排序 - javascript

javascript - 有没有办法在池化 A 型框架实体上启动 tick() 循环,或者我应该手动管理?

javascript - 更改对象子元素的颜色或位置

ruby-on-rails - 我在我的 Rails 应用程序的 Assets 管道中包含 AFRAME 时遇到问题

Angular.io + AFRAME。 Three.js "Cannot find namespace ' TREE' 的输入错误

javascript - 当我的 Javascript 函数运行时,我的 A-Frame 没有渲染。我怎样才能让它同时渲染?