0

currently i have a game in which i am try to play a sound when ever the player presses the arrow key to moves the car which is handled by an enter-frame function, but what ends up happening is that the sound is started again over and over and playing over each other as long as the key is held down eventually crashing the game. Below is the code i am using to play/stop the sound as well as the code for the enter-frame function (animate).

function sounds(): void
{
    if (forwardPressed == true)
    {
        carMoveSound.play(pausePos);
        trace('play sound');
        return;
    }

    if (forwardPressed == false)
    {
        SoundMixer.stopAll();
        trace('stop sound');
        return;
    }
}

function animate(e: Event)
{
    moveCar();
    checkHitBoundry();
    checkHitObstacle();
    checkLapFinish();
    sounds();

    if (gameOver)
    {
        endGame();
        return;
    }
}

Any help would be greatly appreciated.

  • You could observe if the sound has finished, and only then let it to play again. [https://stackoverflow.com/a/15258666/4756930](https://stackoverflow.com/a/15258666/4756930) - In audioComplete you'd f.ex. set `carSoundPlaying = false;` and check its value in sounds function; if false, set it to true and play the soundchannel. – kaarto Sep 11 '17 at 05:47
  • @kaarto No, not really. You can have as many as 32 sound channels, all from the same **Sound** object. The problem with code above is that it tries to spawn a new **SoundChannel** via **Sound.play()** every frame. – Organis Sep 11 '17 at 06:03
  • @Organis Indeed that's true. I ment to hint him to create a SoundChannel manually and re-using it, but my outcome wasn't exactly what it should have been. And to be honest I forgot that playing Sound creates new SoundChannel instance as I never play 'just' Sound objects. – kaarto Sep 11 '17 at 06:28

0 Answers0