Question

I am fairly new to using sounds, and I am able to play a sound, but I am having troubles with all of the sound clip threads that java makes when I play a sound. I would like to know how I would get all sounds to run on one thread, or to die once it is done playing.

I am currently running this code to actually play a sound, creating a new instance of everything when I call the play() method:

private AudioInputStream as;
private Clip c;

public synchronized void play(final SoundType type) {
    reset();
    try {
        as = AudioSystem.getAudioInputStream(getSound(type));
        c = AudioSystem.getClip();
        c.open(as);
        c.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

What I am able to do with this, is it enables me to play multiple sounds at once, by creating a new instance of each item at once. Only problem is that it creates multiple threads in the process, and the program ends up with so many threads when playing different sounds.

Is there a more efficient method, or an approvement I could do to my current method, that would allow me to play multiple sounds at once but at the end it will kill that clip thread, or maybe have one thread that handles all sounds?

Was it helpful?

Solution

You can write your own audio mixer. It isn't that hard. The audio data is extracted from the audio files, and the frames are summed before being output to a single SourceDataLine.

Or, you could use TinySound (code available on github). It is a nice clean implementation of exactly this sort of mixing.

One benefit of mixing to a single output: some systems (some Linux) do not support multiple outputs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top