简体   繁体   中英

Java Clip (sound) 'echoing' and not playing efficiantly

SOLVED

There was a problem with Runnable, so there were acually TWO game threads running at the same time. (Equals problem!) So the second thread that hit the audio player made the error, and thats why it sounded echoy- it was playing from two different threads!

I also am using SourceDataLine, as suggested, to enable longer sound clips.

Original post-


When this code fires, an error pops up saying

IllegalStateException: Mixer is already open

at the clip.open() line. I have put in every measure to check if the code is being ran twice, it is not. However, even with the error, the sound still plays. On longer clips (30 seconds) it sounds like theres 2 sounds playing, one right after the other. On REALLY long clips (3 minutes) the sound stutters.

( stringFile is a String , such as "example.wav" )

File soundFile = new File(stringFile);
AudioInputStream inputStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = inputStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(inputStream);
clip.start();
playing = true;

If this question was already posted, I am very sorry. I have searched and I found no thread similar to this one.

Just checking, but part of the point of using a Clip is that you can keep the Clip in memory and call it multiple times, without having to reload it from a file.

Thus, to start and stop, you would use myClip.open(), myClip.start(), myClip.stop(), and to play it again, myClip.setFramePosition(0) and myClip.start() if I read the Tutorial correctly. (I just work with SourceDataLines, usually, so forgive me if I have this wrong.)

If you are reloading it from a file every time, could that cause or contribute to the problem? In any case, I'd consider switching to a SourceDataLine. Among other things, this eliminates the overhead of having to load the entire clip into memory before it can start playing.

30 seconds is a lot of RAM, by the way. 30 * 44100 = 1.323 MB (and that's with just 1 byte per frame, a more common wav format is 4 times that size). Thus, with your longer sounds you might be taxing your RAM to the point of page swapping which would cause stuttering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM