Audio resources wont play after export to jar - java

Okay, so I have a simple program that loads audio files and plays them.
I have this for loading my audio files
Clip c1 = null;
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(songPaths[k + 1]).getAbsoluteFile());
c1 = AudioSystem.getClip();
c1.open(audioInputStream);
} catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
It runs fine in my intelliJ, and when I look to build artifacts and try to run the jar that's made it fails to load the resources. My songPaths array looks like this:
private final String[] songPaths = {"res/fcpOriginal.wav", "res/fcpRemix.wav",
"res/ibizaOriginal.wav", "res/ibizaRemix.wav",
"res/pohOriginal.wav", "res/pohRemix.wav",
"res/sugarOriginal.wav", "res/sugarRemix.wav",
"res/wavesOriginal.wav", "res/wavesRemix.wav"};
I'm not quite sure what's going on. Any help would be greatly appreciated.

So if I'm understanding your directory hierarchy correctly, you have the following:
src
out/artifacts/nameOfProject_jar.
res
You should put a copy of your res folder in to the nameOfProject_jar folder. Because the working directory for your application is now your nameOfProject_jar folder, so when you are using relative paths like you are, it will look for the res folder in nameOfProject_jar directory instead. :)

I figured it out. FOR ANY FUTURE RESEARCHERS!
I changed
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(songPaths[k + 1]).getAbsoluteFile());
to
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(getClass.getResource(songPaths[k + 1]));

Related

file not found or syntax incorrect when using Main.class.getResource("notification.wav").getFile()

I am trying to play a .wav file but having trouble doing so with a relative path function.
public class Main {
public static void main(String[] args) {
playSound();
}
public static void playSound() {
try {
File file = new File(Main.class.getResource("notification.wav").getFile());
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error playing sound.");
ex.printStackTrace();
}
}
}
If I run the code above in IntelliJ, I receive the error:
java.io.FileNotFoundException: C:\Users\Dominik\Documents\IntelliJ%20Projects\nbbot\out\production\nbbot\com\company\notification.wav (The system cannot find the path specified)
If I run my built .jar application, I receive the error:
java.io.FileNotFoundException: file:\C:\Users\Dominik\Documents\IntelliJ%20Projects\nbbot\nbbot_jar\nbbot.jar!\com\company\notification.wav (The filename, directory name, or volume label syntax is incorrect) in Java?
The .wav file an the Main class, where I run the code snipped are in the same folder:
nbbot > src > com > company > Main.java; notification.wav
It's strange, because the paths are correct and there should be no problem to just read the file.
I also tried Main.class.getClass().getResource("notification.wav").getFile(); and .getPath() but no luck either. If I just use new File("notification.wav") and put the .wav the project folder nbbot the audio plays as intendet, but only in the IDE.
Your plan is broken. resources aren't usually files. Calling .getFile() on a resource is usually going to get you broken code. For example, when pack up your app into a jar, boom, breaks. a java.io.File object can only represent an actual file.
Just about every API also lets you pass a URL or an InputStream instead of a File, use those - those are abstractions that apply to all resources.
getAudioInputStream is just such a method, fortunately. It has overrides for em. Write this:
try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
Main.class.getResource("notification.wav"))) {
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
This will probably fix this problem and will definitely mean that your code will continue to work once your files are packed up into a jar.
NB: InputStreams are resources that must be closed, hence, you need to use try-with-resources, or your app will eventually hard-crash due to running out of OS handles after playing enough audio.

Java: playing wav from resources

I want to create a jar with wav files on it so I can play them as resources.
While running Eclipse, I first declare the folder locally like this:
File folderStimuli= new File("C:\\Users\\Martin\\Stimulus");
public void play(File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException{
if (status != PLAYING) {
clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
clip.open(ais);
clip.addLineListener(this.lineListener);
status = PLAYING;
this.timeStart=System.currentTimeMillis();
clip.start();
}
}
I now have my files on the project folder, namely, /src/main/resources and want to create a jar that reads the files from there. As a beginner, I don't have a clue how to do it. Would you please be so kind indicating what do I have to change here in order to work?
thank you really much!
Martin

Jar not reading audio files from inside the jar file

Okay, I've been at this for hours, I've checked other questions for help and I've tried all of the suggestions but none seem to work.
I am packaging a folder (called "audio") into my project with a bunch of .wav files in it. I am trying to reference those files, however they never get referenced inside the JAR, only outside in a separate folder called "audio".
try {
Clip clip = AudioSystem.getClip();
InputStream inn = this.getClass().getClassLoader().getResourceAsStream("/audio/" + rangod + ".wav");
AudioInputStream inputStream = AudioSystem.getAudioInputStream(inn);
clip.open(inputStream);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(-10.0f);
clip.start();
} catch (Exception e1) {
e1.printStackTrace();
}
The problem child seems to be
InputStream inn = this.getClass().getClassLoader().getResourceAsStream("/audio/" + rangod + ".wav");
From what I've seen on other questions similar to this, having the "/" in front of "audio" is supposed to reference the audio folder INSIDE my jar file where as removing the "/" from in front of "audio" is supposed to reference the audio folder in the same directory as my jar file (ie: /desktop/audio)
Both methods seem to reference the same folder outside of my jar, and neither the one inside my jar.
My hierarchy is this:
audio
----[audio files]
net
----fragbashers
--------rgp
------------[class files]
I fixed the issue, it was a really easy fix that I was overlooking. All my WAV files were saved in all lower case and I hadn't been converting the picked characters string to lowercase, so it didn't think the file existed.

url for audioInputStream seems empty

I am trying the following code to play an mp3. The file is in the correct folder. An exception is thrown when opening the file.
Any ideas what could be wrong?
When trying to print the url on the third line it gives me a null pointer exception.
I am compiling with 1.8 to a min compat version of 1.6. Could this be related?
AudioInputStream audioIn = null;
URL url = this.getClass().getResource("./data/1.wav");
System.out.print(url.getFile());
try {
audioIn = AudioSystem.getAudioInputStream(url);
//audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(soundFile));
}
catch(Exception ex) {System.out.print("exception opening file");}
try{
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
}
catch(Exception ex)
{
System.out.print("exception mediaplayer");
}
}
Instead of using a String var, you could use a Clip object. With Clip, it worked for me.
Oh I had to put the data folder in the src directory.
Still a problem though: when I compile as a jar file, it does not find the data folder. And I want the user to be able to put different things in there.
A URL can see into Jar, unlike a File address. So, you should be fine using the URL to obtain the file.
Two possible problems:
(1) if the file is an .mp3 and you are trying to load a .wav, there will of course be a mismatch as 1.mp3 <> 1.wav.
(2) putting the data into the src folder is not enough. It must also be in a subfolder of the folder that contains the "this" that you refer to. For example, if your code is in package "foo", the place to put the file would be src/foo/data/1.wav.
Do you have a library to decode the .mp3? If so, something like JavaZoom should work.

Audio clip not playing when compiled

in a recent discussion on StackOverflow I was trying to resolve an imageicon issue that didn't display images after compilation, only when ran in eclipse. This problem was solved by changing the location of my resources folder from my project folder to the src folder. I was also taught to get my resources with the following code:
ImageIcon img = new ImageIcon(getClass().getResource("/resources/picture.jpg"));
Without looking at how I had coded my audio method, I asked if the method of putting resources inside the src folder was the same for all types of resources, in which I was told, pretty much. Anyway, now I have got to my audio code, I am a little unsure of how to implement the "getClass().getResource()" line into it.
As it stands my audio works as intended, when ran in eclipse, but when compiled it has the same issue as the images used too. I know that the problem is very similar, but I believe it is a matter of coding, or lack of it. Any pointers, or examples will be greatly appreciated. Thanks.
SOURCE CODE:
public static void menusong(){
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("sounds/dre2.wav"));
bgclip = AudioSystem.getClip();
bgclip.open(ais);
bgclip.start();
try {
Thread.sleep(33000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
Right, got it! Instead of this:
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("sounds/dre2.wav"));
I changed it to this:
AudioInputStream ais = AudioSystem.getAudioInputStream(classname.class.getClass().getResource("sounds/dre2.wav"));
All is now working beautifully when compiled, thanks anyway for the help, much appreciated.

Categories

Resources