Issue
Here is the code for class SoundTest:
package code;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class SoundTest {
public static void main(String args[])
{
File sound = new File("main//Sounds//open1.wav");
playSound(sound);
}
public static void playSound(File f)
{
try {
File file = f;
if(file.exists())
{
AudioInputStream audio = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
//clip.close();
}
else
{
System.out.println("Can't find file");
}
}
catch(Exception e)
{
System.out.println("Didn't work!");
}
}
}
When I run it, there are no errors or exceptions, and it never says "Can't find file" or "Didn't work!". But I don't hear a sound. Do I have to change some sort of setting in Eclipse to make the sound audible, or am I doing something wrong? I'm pretty sure the sound file is located in the right place.
Solution
That is not eclipse problem. File is being opened and played by java, but even before that audio clip completes playing, the program is getting terminated - Meaning java program is not waiting for the clip to complete playing
Your method is missing one single line of code to give you what you want, see below
Thread.sleep(clip.getMicrosecondLength() / 1000);
So, after adding this line your code should look like this and you will hear your music
AudioInputStream audio = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
Answered By - Chandan
Answer Checked By - Marie Seifert (JavaFixing Admin)