I'm new to programming and I couldnt figure out how to play a sound clip. The code run smoothly but there is no sound coming out from intellij.
Here's my code
package ProjectWumpus;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
public class testClass {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
File file = new File("C:\\Users\\Correct_Answer_Sound_Effect.wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audiostream);
clip.start();
My audio from my pc is working fine.
In the comments, both respondents pointed out that the program closes before the
Cliphas a chance to play.Clipsimmediately return control back to the main thread. The code which executes the playback is on adaemonthread.Daemonthreads will not hold open a program that is ready to close.FWIW, Here is perhaps a better way to test. In the following code a simple GUI: a button that plays the sound. This is a more typical of how clips are used.
I recommend using
URLoverFilefor thegetAudioInputStreammethod. In this case, it's assumed the audio resource is in the same directory as the class that is calling it. AURLhas the benefit of working when the class is packaged in a jar (unlikeFile).