views:

230

answers:

1

If I have a java.applet.AudioClip object I can call play on it to play it once. But if I call play multiple times then the clip will simply keep restarting. The only way to get around that seems to be to load multiple instances of the same sound file. That seems wasteful of memory. In a game, if I have 20 explosions occurring then I'd have to load 20 instances of the sound file.

I took a quick look at javax.sound to see if using it instead of AudioClip would help here. I don't see anything that indicates that it supports playing the same clip multiple times simultaneously.

Is it possible to do without loading the same sound file multiple times either with the simple java.applet.AudioClip or with the javax.sound stuff?

+3  A: 

Check here http://forums.sun.com/thread.jspa?threadID=5370182

if you're using a clip, you'll have to maintain one copy per object that needs to play the sound concurrently. You could keep one master copy, and then create copies of the clip as necessary to play them, and then just dump the copies to decrease memory consumption.

A second idea would be to write your own Clip class. Esentially, all you would need to do is dump some sound data onto a TargetDataline to play it. It'll handle the buffering and playing at the correct speed itself. If that's all you did, you should be able to dump multiple times from the same instance and play it multiple times.


read the raw sample data into a byte array and whenever a sound needs to be played I read the data from the array with a ByteArrayInputStream which is fed into an AudioInputStream. After the playback has finished I just close the Clip and no system resources are wasted.

lalith
the byte array idea is pretty clever
warren