I am trying to open a .wav file and play it using a Clip. But when I call myClip.open(...), the thread freezes and never resumes. No errors are thrown. Here is a simple version of my code:
try {
AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
myClip = AudioSystem.getClip();
myClip.open(mySound); //This is where it hangs
myClip.start(); //This is never executed
} catch (Exception e) {e.printStackTrace();}
EDIT: An alternate version of my code (also doesn't work):
Clip myClip = null;
new Thread(new Runnable() {
public void run() {
try {
AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
myClip = AudioSystem.getClip();
System.out.println("Before open");
myClip.open(mySound); //This is where it hangs
System.out.println("After open"); //never executed
//This thread runs indefinitely, whether or not clip.start() is called
} catch (Exception e) {e.printStackTrace();}
}
}).start();
try{ Thread.sleep(1000); }catch(Exception e){} //give it a second to open
myClip.start(); //Executed, but doesn't make a sound
System.out.println("Started clip");
Output:
Before open
Started clip
I know what causes this, but I can't figure out a way the thread from freezing eternally. It freezes because the sound drivers on my computer occasionally stop working, and prevent any sound from any program from playing. I just need some way to force the clip.open method (or thread) to timeout after about 2 to 3 seconds. Calling clip.start() in another thread works, but plays no sound because the clip hasn't opened. And the thread containing clip.open(...) runs forever, even after calling clip.start().