I want to play some sound in java using this code bellow. That sound is in WAV format so I think that this code should work fine, but instead of playing sound it simply does nothing. There is no even error on my console. So can someone help me to make this code play sound. (this sound is included inside one package in my src file)
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Clip clip = AudioSystem.getClip();
File file = new File("C:\\Users\\Jovan\\Desktop\\song.wav");
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You have to wait for the clip to play and end. You can also create some Listener but that's more complicated. When the clip finishes playing (isActive() is false) you end.
public class P {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("started");
Clip clip = AudioSystem.getClip();
File file = new File(".......................wav");
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
clip.open(inputStream);
clip.start();
while(clip.isOpen()) {
try { Thread.sleep(2000); } catch(InterruptedException ie) {}
if(!clip.isActive()) break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}