I want to play a .wav file using java code which is in a jar file as resource. My code is look like this -
try {
URL defaultSound = getClass().getResou
like Kal wrote :
- InputStream is = getClass().getResourceAsStream("......");
- AudioInputStream ais = AudioSystem.getAudioInputStream(is);...
I did just that and it didn't work at first but the problem of "java.io.IOException" was that I used File.separator and for some reason win 8.1 couldn't handle "\\"...
public AudioInputStream getSound(String fileName){
InputStream inputSound;
AudioInputStream audioInStr;
String fs = File.separator;
try {
absolutePath = fs +packageName+ fs +folderName+ fs +fileName;
inputSound = getClass().getResourceAsStream(absolutePath);
//if null pointer exception try unix, for some reason \\ doesn't work on win 8.1
if(inputSound == null) {
absolutePath = "/" + packageName + "/" + folderName + "/" + fileName;
inputSound = getClass().getResourceAsStream(absolutePath);
}
audioInStr = AudioSystem.getAudioInputStream(new BufferedInputStream(inputSound));
return audioInStr;
}
Change:
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
To:
System.out.println("defaultSound " + defaultSound); // check the URL!
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(defaultSound);
this worked fine for me:
public void playSound() {
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream(new File(
getClass().getClassLoader()
.getResource("com/kaito/resources/sound.wav").getPath())));
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}