LWJGL Forum

Programming => OpenAL => Topic started by: Red XIII on February 23, 2010, 20:27:22

Title: How can I check whether a sound is playing or not?
Post by: Red XIII on February 23, 2010, 20:27:22
Hi guys.

I'm new to lwjgl and I have read the 2D/3D Asteroids Tutorial from the doucumentation site. Now I try to add and modify some things.
I added some background music, which starts playing when I enter the InGameState. But how can i check if a specific sound (my background music) is playing?

My current solution:

GameState:

public class MainMenuState implements IGameState {

private Sound main;

@Override
public void enter(GameWindow window) {
playMainMusic();
}

@Override
public void init(GameWindow window) throws IOException {
main = SoundLoader.get().getOgg("res/sound/main.ogg");
main.setLength(177);
}

@Override
public void update(GameWindow window, int delta) {
playMainMusic();
}

private void playMainMusic() {
if (!main.isPlaying()) {
main.play(1f, 0.8f);
}
}


SoundObject:

public class Sound {

private SoundLoader store;

private int buffer;

private int length = 0;

private long startplaying;

Sound(SoundLoader store, int buffer) {
this.store = store;
this.buffer = buffer;
}

public void play(float pitch, float gain) {
startplaying = System.currentTimeMillis();
store.playAsSound(buffer, pitch, gain);
}

public void setLength(int lengthInSec) {
this.length = lengthInSec;
}

public int getLengthInSec() {
return length;
}

public boolean isPlaying() {
return startplaying + length * 1000 > System.currentTimeMillis();
}
}


Basically I save the length of the sound in the soundobject and when i start the sound, i save the current time. Finally, if i want to know whether the sound is playing or not, i compare the current time with the starttime + length.

Is there a better way?

Cya,
Red XIII
Title: Re: How can I check whether a sound is playing or not?
Post by: Cottonwood on December 14, 2010, 06:53:33
Cause I'd the same question I want to report here, though the thread is rather old.

I found a better solution here: http://lwjgl.org/wiki/index.php?title=Examples:SpaceInvaders_SoundManager

  public boolean isPlayingSound() {
    return AL10.alGetSourcei(sources[sources.length-1], AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;
  }