Reputation: 103
I have a few elements that play a sound on click or mouseenter. I’d like to mute these sound effects whenever the user clicks on a button and unmute when the button is clicked again.
Example: https://pebble-kiss.glitch.me/
So far I’ve only been able to mute the background audio but not the mouseenter & click audio. Is there even a way to do this or do I have to manage all of the sound in 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;
});
}
});
Upvotes: 3
Views: 893
Reputation: 14645
Your component is switching between stopping and playing sounds. If you want to mute them, you can just flip the volume.
Since you have different volumes for each element, you should store them. Make sure the elements are loaded before you try to grab the volumes !
When you want to mute, just iterate through the elements, and switch between 0 (muted) and the stored value:
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
});
}
});
glitch here
Upvotes: 3