Toggling a Constant Sound

I was wondering how you can simply script a key to start a sound looping, but pressing it again to stop it. And also make it not rely on the time you hold it (pressing/holding the key will turn it on, and vice versa).

Any code examples?

Thank you in advance!

No code examples for this exact situation unfortunately (maybe we should add some more UI specific ones :thinking:)

It’s effectively a toggle button that plays/pauses the sound.

I would have a Boolean variable that stores whether the sound is playing or paused. Listen to the click event on the button and based on Boolean variable, play or resume the sound

I tried various codes, but even this (which has no problems in the console) will not work:

if (app.keyboard.isPressed(pc.KEY_E) && grab === false) {
        grab = true;
    }
    
if (grab === true) {
        this.entity.sound.play('Grab');
    }

if (app.keyboard.isPressed(pc.KEY_Q)) {
        grab = false;
        this.entity.sound.stop('Grab');
    }  
  

Try using wasPressed instead of isPressed. wasPressed only checks if the key was pressed once. Use wasReleased to check if the key was let go of.

Hmm, so this is my sample code:

//Variables
var grab = false;

Script.prototype.initialize = function() {
    this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown,, this);
    this.app.keyboard.on(pc.EVENT_KEYUP, this.onKeyUp, this);
};

Script.prototype.update = function(dt) {
    if (this.app.keyboard.wasPressed(pc.KEY_E) && grab === false) {
        this.entity.sound.play('Grab');
        grab = true;   
    }
    if (this.app.keyboard.wasPressed(pc.KEY_Q) && grab === true) {
        this.entity.sound.stop('Grab');
        grab = false;
    } 
};

Don’t forget to change Script to whatever your script’s name is.

1 Like

This probably won’t work because the sound is now constantly started.

Little typo in the first line of the initialize function @DevPlex01.

@DevPlex01
Is there a better way to activate the boolean “loop” for the sound string? (see script)
I desire for this to loop when it is to be on, on turn off and not loop when off.
(Not sure if there is a simpler way to do that)

if (this.app.keyboard.wasPressed(pc.KEY_E) && grab === false) {
        this.entity.sound.play('Grab' , loop = true);
        grab = true;   
    }
if (this.app.keyboard.wasPressed(pc.KEY_Q) && grab === true) {
        this.entity.sound.stop('Grab' , loop = false);
        grab = false;
    }

You could try seeing if something like this.entity.sound.loop exists. You can set it to true when you want it to loop and set it to false when you don’t want the sound to loop.

1 Like