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:

Load all of your sounds ahead of time, when the game is loaded.

Then just play the already-loaded sound whenever you need to.

TinySound

The suggestions from both KevinWorkman and nsigma are good.

Many posts on TinySound can be found here on JGO (via a local search).

For a javax.sound.sampled.Clip, to expand on what KW wrote: the data for the Clip should be loaded only once, and well before the calling of the play command. After the play command, you can use setFramePosition or setMicrosecondPosition to get the Clip ready for an additional playback. As your code stands, you are unnecessarily reloading the complete file into memory before commencing the play start.

If sounds are too large to hold in memory, playing back via a SourceDataLine is better than a Clip. The SourceDataLine will start processing the file data as soon as it gets the data rather than waiting for the entire file to load to memory before being able to play. It is very responsive but uses a slightly larger amount of cpu than Clip playback.