Playing an AudioInputStream multiple times

I'm making a program that loads audio files and mix them together, producing an AudioInputStream object. I'd like to play the sound as many times as the user wants it, but I found that the AudioInputStream is emptied once is read, so I'm not able to replay it.

I solved the problem writing the content of the AudioInputStream into a temp file, and reading the file each time I want to play the sound. Is there any other better way to play an AudioInputStream more than once? Note that ais.markSupported() returns false, so I can't use reset().

Thanks for the reply OrangeDog. What's easy to say it's usually harder to do... :D I'll explain you now.

Initially, I was using a Clip instead a SourceDataLine. But Clip has its limitations, and I got a Java heap error when reading large files. I am using SourceDataLine with buffers and is working perfectly, that's not a problem.

What I want to do is to play a sound multiple times, as in a Sound Player. When the user press stop and then play again, the song is replayed. The problem is that the AudioInputStream is emptied while playing the sound, so I have to reload the song each time. Now I'm using a temp file for that, but I'd like to do it in memory.

Originally Posted by OrangeDog

You don't need to use a file, just copy the data into an array in memory.

Yes, this is what I want! The problem is... how? This is my guess, but I get an Java.io.EOFException when executing getAudioInputStream(bais) (the last statement):

Hmm, can't quite see what you're doing there - things seem a little over complicated. Although, if you're getting heap errors, the audio is probably too large to hold in memory by any method. The way I'd do it (omitting error handling and some refinements) is:

If heap overflow is a relatively rare problem, try splitting the data into smaller chunks and building a memory-sensitive cache with java.lang.ref.SoftReference. Then you wouldn't have to reload as much data. Whether this would work depends entirely on the rest of your application of course.

I discovered the reason for the heap overflow: when I was trying to obtain the stream duration (getFrameLength / getFrameRate), it came out that the actual duration was longer than 24000 secs. :eek: It meant that the sound I was playing lasted more than 6 hours... The sound file actually lasted only 4 seconds, so I suppose it's a problem with the file format. I recorded it in WAV format with gnome-sound-recorder, if someone is needed to be blamed. :P

So it looks like the impediment to work with Clips has disappeared. However, there's always a limitation: as the jsresources FAQ states (three messages more and I'll be allowed to put links, I promise), Clip can't handle files bigger than 5 Mb. So it is more than probable that I'll come back to SourceDataLine and I'll put into practice your pieces of advices. I'll post as soon as I have any result, thanks again for your help.