I have looked at countless different StackOverflow answers as well as answers from other sites, but none of the solutions have fixed my problem. I cannot for the life of me get my .wav file to play.
Here is my code:
Sound class:
public class Sound {
/**
* Static file paths for each sound.
*/
public static String stepSound = "/resources/step.wav";
/**
* Audio input stream for this sound.
*/
private AudioInputStream audioInputStream;
/**
* Audio clip for this sound.
*/
private Clip clip;
/* -- Constructor -- */
/**
* Creates a new sound at the specified file path.
*
* @param path File path to sound file
*/
public Sound(String path) {
// Get the audio from the file
try {
// Convert the file path string to a URL
URL sound = getClass().getResource(path);
System.out.println(sound);
// Get audio input stream from the file
audioInputStream = AudioSystem.getAudioInputStream(sound);
// Get clip resource
clip = AudioSystem.getClip();
// Open clip from audio input stream
clip.open(audioInputStream);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
/* -- Method -- */
/**
* Play the sound.
*/
public void play() {
// Stop clip if it's already running
if (clip.isRunning())
stop();
// Rewind clip to beginning
clip.setFramePosition(0);
// Play clip
clip.start();
}
/**
* Stop the sound.
*/
public void stop() {
clip.stop();
}
}
Constructor call that leads to error:
// Play step sound
new Sound(Sound.stepSound).play();
I know this isn't the first time a problem like this has been asked or answered on this website, but I've been trying other solutions for hours at this point and all I've found is pain and frustration. I can post more code if needed. Thanks in advance.
EDIT: I have unpacked the .jar file and confirmed that the file is indeed there. The problem is that the URL ends up being null, and so a NullPointerException
is thrown.
EDIT #2: Added more code in case there's another problem.