Reputation: 941
I am currently bussy creating a videogame as a small side-project to keep my programming skills on point for university. One aspect of videogames are sound effects, and I'm boggling my mind around how to do this best in Java.
Currently I am using the Clip class for sound effects, here's a preview of the (very basic and common) code I'm using:
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(path));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
if(loop)
{
clip.loop(Integer.MAX_VALUE);
volumeControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
setVolume(volume);
launched = true;
}
else
{
clip.start();
volumeControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
setVolume(volume);
running = true;
CoreTime.sfx.add(this);
}
} catch(Exception e){System.out.println(e + "=-=-=-=-=-=-=-=-=-=run SFXPlayer");}
The problem with the Clip class however is that it creates a new Thread for itself on which it plays the audio. Having a high count of clips being required to be played at the same time can thus spike the amount of threads created and even possibly freeze the game for a bunch of seconds. With some analysis, I've gotten the thread-count to go up to 60 threads when playing lots of sound effects at the same time.
Now obviously this is unwanted behaviour and I am wondering how I can get around this, and implement sound effects more efficiently. Are there methods or ways that you guys know of, that don't create this insanely high amount of threads where I am able to play lots of sound effects at once? Some help would really be appreciated!
Upvotes: 0
Views: 767
Reputation: 3407
If JavaFX is an option, it might be a good idea to switch to it as it provides a good range of features for audio playback. From official documentation:
AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();
You can also use .wav
files, which are a popular choice for sound effects. For more information visit javadoc.
Upvotes: 1