I have 2 sets of sounds, which are supposed to play only when a flag (SndFlg) is set (by toggling the S key). The first set is toggled on/off by the SndFlg. The second set is turned on only if the SndFlg is on and only if the Spacebar is depressed.
If I enable the SndFlg (which starts the first set of sounds) and then press the Spacebar (to start the second set of sounds), I get the following error notice: THREE.Audio: Audio is Already Playing
Is there a way to eliminate this error? Does three.js allow you to use separate sound channels which can be turned on/off seperately?
The two sets of sounds are connected to 2 different objects and the objects are connected to a single visible object. Here is the sample code:
let listener = new THREE.AudioListener();
camera.add(listener);
// Engine
let EngSnd = new THREE.PositionalAudio(listener);
EngSnd.setVol(0.5);
let EngMsh = makMsh(); // This makes a basic mesh
EngMsh.add(EngSnd);
EngMsh.position.z = -5; // Sound is in front
AirObj.add(EngMsh);
// Guns
let GunSnd = new THREE.PositionalAudio(listener);
GunSnd.setVol(0.5);
let GunMsh = makMsh(); // This makes a basic mesh
GnLMsh.add(GunSnd);
AirObj.add(GunMsh);
I want to toggle all sounds on or off whenever I press the S key.
I want the first set of sounds to play or stop playing whenever the SndFlg is toggled on or off.
I want the second set of sounds to play only when the SndFlg has been toggled on and when the spacebar is depressed. These sounds will be turned off when the spacebar is released, regardless of whether SndFlg is toggled on or off.
Similarly, when I toggle the SndFlg on, it will only turn the second set of sounds on if the spacebar is already depressed.
Here is the sample code:
//Keyboard Input
// Guns - Spacebar Down
if (event.keyCode == K_Guns) {
if (SndFlg) GunSnd.play(); // ### This is what causes error (Audio Already Playing)
GunFlg = 1;
}
// Guns - Spacebar Up
if (event.keyCode == K_Guns) {
GunSnd.stop(); // Stop - regardless of whether all sounds are on or off
GunFlg = 0;
}
// Sounds - If S Key Pressed
if (event.keyCode == K_Soun) toglSoun(); // S Key
//. Toggle Sound On and Off
function toglSoun() {
SndFlg = 1 - SndFlg; // 0 = Sounds Off, 1 = Sounds On
if (SndFlg) { // Off to On
EngSnd.play();
if (GunFlg) GunSnd.play(); // Only play if spacebar already depressed
}
else { // On to Off
EngSnd.stop();
if (GunFlg) {GunSnd.stop()}; // Only stop if spacebar already depressed
}
}
Should I be using 2 listeners? (Does three.js have sound channels?)
Should the sound meshes not be attached to the same parent mesh?
(Note that I am using meshes, rather than 3Dobjects - if htat makes a difference.)
THANKS! This works perfectly. No more error messages!