Java Swing / AWT Sounsd

Hi all. I need to know how to play sounds with good timing. I’m currently able to play sounds but I use this code:


    public static synchronized void play(final InputStream inputStream) 
    {
        // Note: use .wav files             
        new Thread(new Runnable() { 

            public void run() {
                try {
                    Clip clip = AudioSystem.getClip();
                    AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream);
                    clip.open(audioStream);
                    clip.start(); 
                } catch (Exception e) {
                    System.out.println("play sound error: " + e.getMessage());
                }
            }
        }).start();
    }

If I use this for playing background music is OK. But if I use this for playing things like punch (a short sound that must be repeated often) the timing is wrong and often the sound is not even played.

I think the issue is related with starting a new thread. Is there a way to mix sounds, maybe, in real time?

By the way, I’m not loading the sound from file, I have it cached in a byte array that I wrap into an input stream an call this method.

Any help would be appreciated :slight_smile: