javafile-ioaudioinputstream

Java Music File returns "(No such file or directory)" but path seems correct


I'm working on a Java game project right now, and I'm trying to import music. However, I can't seem to get it working:

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Music {

public static void playSound(String name) {
    try {
        
        System.out.println("music is now playing");
        File file = new File("audio/" + name + ".wav");
        AudioInputStream stream = AudioSystem.getAudioInputStream(file);
        Clip clip = AudioSystem.getClip();
        clip.open(stream);
        clip.start();

        // sleep to allow enough time for the clip to play
        Thread.sleep(10);

        stream.close();

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

}

The above is my code for my music.java class, which is then called in my main game.java class.

public static void main(String[] args) {
    // instantiate this object
    Music.playSound("ahem");
    Game game = new Game();


} // main

But my output returns

music is now playing 
audio/ahem.wav (No such file or directory)

I'm fairly certain that my .wav file is placed in the right spot (in an "audio" folder inside my "bin" folder, so I'm not sure what's going on.


Solution

  • I figured out what I was doing wrong! I needed to include "bin" before my "audio/" + name + ".wav" path.

    i.e., bin/audio/name.wav