1

I have recently been learning how to add sounds in java. Currently, I have this code that works, but it isn't always playing at the right time, or sometimes it doesn't even play at all. How could I get the sound to play each time the play() method is fired at the right timing? This happens every time I click on a component, by the way.

public class Sound {

    private File sndFile0;
    private AudioInputStream au;
    private Clip cl;
    private DataLine.Info info;

    public Sound() {
        try {
            sndFile0 = new File(getClass().getResource("/sound/vir1.wav").toURI());
            au = AudioSystem.getAudioInputStream(sndFile0);
            info = new DataLine.Info(Clip.class, au.getFormat());
            cl = (Clip) AudioSystem.getLine(info);
            cl.open(au);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        cl.start();
        cl.setFramePosition(0);
    }
}
CoderMusgrove
  • 604
  • 8
  • 18
  • just restart on Type.STOP. http://stackoverflow.com/questions/557903/how-can-i-wait-for-a-java-sound-clip-to-finish-playing-back – Michael D. Nov 24 '13 at 22:56
  • @MichaelD. It's weird, If I click on the components fast enough or after the clip ends, the sound will restart, otherwise if it's somewhere in the middle it won't do anything. I change the play code to this: http://pastebin.com/KNAmd9Mc – CoderMusgrove Nov 24 '13 at 23:12
  • if it is already playing you want to restart it? that's a stop() reset() and a play() or so... not sure – Michael D. Nov 24 '13 at 23:28
  • After some testing I found out that the `LineListener` didn't do a thing, the only thing that is allowing the sound to play more than once is the `cl.setFramePosition(0)`, which works sometimes. I even tried using `cl.stop` at the beginning of the play method, it didn't help at all. So basically it threw me back to my original `play()` method. – CoderMusgrove Nov 24 '13 at 23:46
  • SOLVED(ish). What I was able to get it to do is each time they click on the component, it will just reload the file. – CoderMusgrove Nov 25 '13 at 05:19

1 Answers1

0

Solved. What I did was I went ahead and loaded the sound file each time the component was clicked on.

CoderMusgrove
  • 604
  • 8
  • 18