Play audio while key is held down?

Hello, I would like to play some audio while a key is held down and stop when the key is released. Right now, it does not play through the duration of the audio (which is 10 seconds long), but keeps starting as it is continuously called in the update() function when the key is pressed. So I would like it to loop through the 10 seconds when the key is pressed but stop when released. Game is here so you can hear it. So far, I have:

import rocket from "../assets/rocket.wav";

// in preload()
this.load.audio("rocket", rocket);

// in create()
this.rocketSound = this.sound.add("rocket", {
    volume: 0.75,
    loop: true
});

// in update() 
} else if (this.cursors.right.isDown) {
    this.rocketSound.play();

I’ve tried several other approaches but nothing seems to be working. Any help would be appreciated.

Thanks!

Try using Phaser.Input.Keyboard.JustDown(this.cursors.right). This method will tell you if the key has just been pressed; currently, you’re playing the sound for every frame on which the key is pressed. You can use !...isDown to check whether to stop the sound.

Note that JustDown will only return true once. If you need to use its result for something else later (or you’re already using it earlier), store it in a variable.

2 Likes

In addition to @Telinc1 s solution you ca still use what you had in update and playvthe sound if only it has not already been started to be played by setting a flag like this.playing and calling play only if it is false. In the scene definition:

    init() {
        this.playing = false;
    }
    update(){
      if (this.cursors.right.isDown) {
        if (this.playing !== true) {
            this.rocketSound.play();
            this.playing = true;
        }
      }
    }
1 Like

@Telinc1 and @fselcukcan thanks for the help.

It now plays the sound when the player is moving and loops through until .stop() is called on rocketSound when the player’s velocity is at rest.

init() {
  isFlying: false,
}

create(){
  this.rocketSound = this.sound.add("rocket", {
      volume: 1,
      loop: true
  });
}

update(){
if ((this.player.vel.x > 0 || this.player.vel.x < 0) &&
this.isFlying === false
) {
  this.rocketSound.play();
  this.isFlying = true;
}

  if (this.player.vel.x === 0) {
      this.rocketSound.stop();
      this.isFlying = false;
  }
}