Search code examples
libgdx

Libgdx Sound when it has finished


This current code when it is the upright state it runs the bass sound repeatedly until it starts distorting the sound and running poorly. How would i dispose of the sound when it has finished running and stopping it run multiple times as i would like the sound only to play once when it has gone into this upright state. Thanks alex.

public void determineState(){
        accelX = Gdx.input.getAccelerometerX();
        accelY = Gdx.input.getAccelerometerY();
        accelZ = Gdx.input.getAccelerometerZ();

        state = "NULL";

        if(accelX < 1 && accelX > -1){
            if(accelY > -1 && accelY < 1){
                if(accelZ > 9 && accelZ < 11){
                    state = "UPRIGHT";
                }
            }
        }

    }

 public void playSound(String soundString){
        System.out.println(soundString);
        if(soundString != "null"){
            sound = Gdx.audio.newSound(Gdx.files.internal(soundString + ".wav"));
            long id = sound.play();
            sound.setVolume(id, 3);
        }else if (soundString == "null"){
        }
    }

Solution

  • You should not create a new sound and dispose it every time you want it to play. This is wasting time reloading it over and over. Store your loaded sounds in an array, or load them with an AssetManager and get the references from there.

    Your playSound method would look something like this:

    public void playSound (String soundFileName){
        sound = assetManager.get(soundFileName, Sound.class);
        sound.play();
    }
    

    By the way, it doesn't make sense to set volume to 3 since it's on a 0-1 scale.

    If you want something to happen only one time when a state changes, than call that method when the state changes, not on every frame as it seems you are doing.

    i.e. do this:

    //...
    if(accelZ > 9 && accelZ < 11){
        state = "UPRIGHT";
        playSound("uprightStateChange.wav");
    }