I'm probably doing this wrong, because there has to be a way to do this.
Here is my current code:
import javax.sound.sampled.*;
public class soundHandler{
soundHandler()
{
}
public void newSound(String sound)
{
new soundThread(sound).start();
}
}
class soundThread extends Thread
{
String soundName;
Clip clip = null;
soundThread(String i_soundName)
{
soundName = i_soundName;
}
public void run()
{
try{
try{
try{
AudioInputStream stream = AudioSystem.getAudioInputStream(ClassLoader.getSystemClassLoader().getResource(soundName));
DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
clip = (Clip)AudioSystem.getLine(info);
clip.open(stream);
}catch(Exception e){System.out.println("err= soundThread_errorLoadingSound ("+soundName+")");}
clip.start();
}catch(Exception e){System.out.println("err = soundThread_errorPlayingSound ("+soundName+")");}
Thread.sleep(150);
//wait for it to finish, then close
while(clip.isActive()){}
clip.close();
}catch(Exception e){System.out.println("err= soundThread_error");e.printStackTrace();return;}
}
}
In soundHandler, the method newSound() is called very frequently, perhaps multiple times per second. This causes it to use a significant amount of CPU for some reason.
Any idea what's going on, or how I can fix it?