Question

I have a program which has to play sounds from a terminal interface.

The code is fairly simple and here it is :

public static synchronized void playSound() {
    new Thread(new Runnable() {
        public void run() {
            File _file = new File("music/sound.wav");

            try (AudioInputStream _audio = AudioSystem
                    .getAudioInputStream(_file)) {
                Clip _clip = AudioSystem.getClip();
                _clip.open(_audio);
                _clip.start();
            } catch ([…] e) {
                // […]
            }
        }
    }).start();        
}

The file is in the music folder which is in my source path.

All work perfectly well when I run the program in eclipse. But if I export it in a .jar file and try it in the windows cmd I get this message :

java.io.FileNotFoundException: music\sound.wav (The system cannot find the path specified)

[edit] The audio files are indeed packed into the .jar, but it still doesn’t work.

Is it even possible to play a sound from the windows prompt? If not, is there one that does?

Thanks, SilverDuck

Was it helpful?

Solution

When the file is packaged into a jar file, it is no longer a File. It needs to be read as a resource. Try changing the code like this

InputStream inputStream = this.getClass().getResourceAsStream("music/sound.wav");
 try (AudioInputStream _audio = AudioSystem.getAudioInputStream(inputStream)) {

OTHER TIPS

Try either not packaging your music in jar (put it alongside) or load your packaged file as a resource.

See Java resource files for example.

Here Loading resources (images) contained in a .Jar file or in the classpath might be a better explanation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top