user2279603
user2279603

Reputation: 85

Java Sound plays once and then doesn't play again

I have a game that needs to be able to play sound. When I click on a button the sound plays, but when I click on the button again the sound doesn't play.

Below is my sound class:

public class Sound {

  public static final Sound select = new Sound("/selectBTN.wav");
  public static final Sound scroll = new Sound("/btn.wav");

  //Phone calls
  public static final Sound call1 = new Sound("/calls/call1.wav");
  public static final Sound call2 = new Sound("/calls/call2.wav");
  public static final Sound call3 = new Sound("/calls/call3.wav");


  private Clip c;

  public Sound(final String filename) {
    try {
         c = AudioSystem.getClip();
         final AudioInputStream inputStream AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(filename));
         c.open(inputStream);
         c.addLineListener(new LineListener() {

           @Override
           public void update(final LineEvent event) {
              if (event.getType().equals(Type.STOP)) {
                   System.out.println("Do something");
               }
            }
           });
        } catch (final Exception e) {
           e.printStackTrace();
       }
  }

  public void play() {
     try {
        new Thread() {
            public void run() {
              if (!title.mute) {
                c.start();
               }
            }
          }.start();
     } catch (Exception e) {
          e.printStackTrace();
     }
  }
}

I use this line Sound.call1.play() to play the sound. Can any one help me to fix this problem?

Upvotes: 1

Views: 851

Answers (1)

Radiodef
Radiodef

Reputation: 37845

Try seeking the Clip to the beginning.

c.setFramePosition(0);
c.start();

Otherwise, the second time you call start there is nothing to play because the Clip is at the end.

Upvotes: 4

Related Questions