0

I want to play a short sound .wav in Java when a timer goes off. The stipulation is that I have a bunch of these timers, and it's very likely that more than one will go off at or near the same time. In that case, I want the sound to play only once and just drop the other requests to play the sound. I don't want the sounds played back to back or anything like that.

Any help on how to code something like that is appreciated.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • 2
    Let's see what you've done first – Sterling Archer Oct 03 '13 at 18:08
  • What are you using for a timer? – erickson Oct 03 '13 at 18:22
  • @RUJordan I haven't done anything yet, but I was going to use the solution in [sound play](http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java) – user1935487 Oct 03 '13 at 18:29
  • @erickson I'm using javax.swing.Timer – user1935487 Oct 03 '13 at 18:32
  • This question is on topic (a practical programming problem). The understanding demonstrated by the question was indeed minimal, but it was enough to solicit working code useful to the asker and others with similar problems. No solutions were attempted, so they were not included. An attempt, and related results can sometimes be helpful, but they are not required, and in this case, not necessary. – erickson Oct 03 '13 at 22:18
  • @erickson Thank you for your sense and understanding. – user1935487 Oct 04 '13 at 18:31

2 Answers2

0

You have to use Read/Write Mutex. look how to used "synchronized":

void methode() {
    synchronized(this) {
        //critical section
    }
}
Goulven
  • 13
  • 5
  • This is likely to cause sounds to be played "back-to-back", since there's no way for a thread to detect whether it had to wait to enter the synchronized block. – erickson Oct 03 '13 at 22:25
0

You can use a ReentrantLock instance around the playing of a sound. This is better than using an intrinsic lock (with the synchronized keyword), because you can detect whether the lock was immediately available. If not, it means another timer thread is already playing a sound, and this request can be ignored.

final class SoundPlayer {

  private final Lock lock = new ReentrantLock();

  ...

  void play(SomeTypeRepresentingTheSound clip) {
    if (lock.tryLock()) {
      try {
        /* Play clip. */
        ...
      } finally {
        lock.unlock();
      }
    }
  }

}
erickson
  • 265,237
  • 58
  • 395
  • 493