Having a Problem playing .WAV files in java

599 Views Asked by At

I was creating what I deemed to be a quite simple program that played a .wav file in Java, but the sound is not playing when the program is started. All of my imports seem to be good, and I am not too sure why it is not playing, and I am starting to wonder if it is a problem with where I placed my files. I have attached both my code, and a screenshot of the location of my files for this project here. Please tell me if more information is needed. Any help is appreciated.

package javaSounds;

import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaSounds {
public static void main(String[] args) {

    File explosion = new File("explosion.wav");
    PlaySound(explosion);

}

static void PlaySound(File Sound) {

    try {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.start();

    } catch (Exception e) {

    }
}
}
1

There are 1 best solutions below

0
On

The problem is not the addressing but that the program finishes and closes before the sound gets played.

The command clip.start() launches and plays the sound on a daemon thread. These threads, even while running concurrently, will not hold a Java program open. Since there is nothing else happening in the program, everything shuts down and nothing is heard.

A simple way to test this is to add the command Thread.sleep(..) after starting the clip. A more usual practice is to trigger the sound from a GUI, where the presence of the GUI keeps the java program alive for the duration of the clip.

If your sound doesn't play with the addition of a sleep pause, then we can look at the addressing. By the way, it's better to get your AudioInputStream from a URL than from a File. If you plan to jar your program and include audio resources as part of the jar, File will be unable to locate those internal resources.