Exported jar file doesn't play sound - java

I made this method to play audio in my class and it works fine.
but for some reason when i export it to a jar file nothing happens.
I tried other solutions but i just get null-pointer exceptions.
does anyone have an idea what i'm doing wrong
public void welcome(){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("sound/garage1.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}

if you load the file like this (not as ressource of a class), the folder "sound" containing the "garage1.wav" has to be located in the working directory when you execute the jar, because new File("") points to the working directory. For example: if you execute the jar with a double click on it, the folder "sound" must have the same parent folder as the jar.

Related

Netbeans- reach resources folder

I know that this question it is similar to this one but it is different. I am trying to open a pdf file that it is in the resources folder of netbeans.
Right now I am in the EventoService.java and I have created a file object to open the pdf file (justificante.pdf) in "Other Resources" folder. I have tried to reach the pdf file like in the link before but it doesn't work because of the constructor. How can I reach it? Thank you in advance.
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File(getClass().getClassLoader().getResource("resources/justificante.pdf"));
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}

Finding files for playing sound

I'm trying to make an application where when I click a JButton, it plays a song. I've already figured out how to specify JButtons. However, I can't seem to find a way to play sound. I'm not going to use sun.audio, so many of the threads that I looked at didnt work. I found many low quality answers. Eventually, I settled on this code.
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
Inside my src folder, I have a folder called "Songs". I changed the file path to this:
/Songs/
Then, I tried calling the function using a wav file:
playSound("song.wav");
And then I get a null error. I believe that this is because it does not recognize the file path. The answer to my problem is most likely very obvious, but somehow I cant find it.
put song.wav in the same folder of your Main class, then the getResourceAsStream will find it.
if you're using eclipse, it can automatically copy the .wav file to the output folder.
You might want to create a class on some different java package so your entry point does not get polluted by assets.
This reading might help you: http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading

Sound will not play in JAR file

I have a problem and I hope you can help me.
Some talk about what I am doing so you know what's going on: So at the moment I'm trying to program a litte piece of software which can play me some music files (mp3 files to be exact, so i'm using the jLayer API). I'm working with Netbeans and I have succesfully imported a music file in the project. If I build my program and open the resulting JAR file with an archive program, I can find my music file in there. My function which I'm using goes like this:
public static String play(String file) {
File test = new File(file);
try {
FileInputStream in = new FileInputStream(test);
Player pl = new Player(in);
pl.play();
return "success";
}
catch (Exception e) {
return e.toString();
}
}
As you can see I'm getting a String with the Path Name and refactor him so I can play the file. I'm calling the function with the following code (the music file is saved in the ressources package):
MP3.play(getClass().getResource("/ressources/angel.mp3").getPath())
So if I start the programm via Netbeans everything works perfectly fine. But if I create a JAR file and start the program nothing happens. The Exception getting is the following:
java.io.FileNotFoundException: file:\C:\Users\Raphael\Documents\NetBeansProjects\MP3\dist\MP3.jar!\ressources\angel.mp3
It says the File does not exist but if I check my JAR the file is there......
Another strange thing I found out is the following: If I use the following function to play the music file:
public static String play(InputStream test) {
try {
Player pl = new Player(test);
pl.play();
return "success";
}
catch (Exception e) {
return e.toString();
}
}
and call the function with the following argument:
MP3.play(getClass().getResourceAsStream("/ressources/angel.mp3"));
Everything works fine in both Netbeans and the final JAR. Can anybody explain me what I'm doing wrong and only the second function works in the JAR version?
It would be really nice if you could help me in this matter.
Greetings,
xXKnightRiderXx
I am assuming that you have 2 packages 1 is src where your .java files is located and other is resources where your sound files is located
So i suggest you to use
MP3.play(getClass().getResourceAsStream("/angel.mp3"));
Because GetResource() automatically finds the resource package

Loading resource files within a jar

What's the best way to load resources (Sounds, images, xml data), that also works from inside a distributed jar file?
I need to load some sounds, images, and xml data, for use in my program. Using
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("~/src/com/example/package/name/assets/TestSound.wav"));
does not work in the jar, for obvious reasons, including the fact that src will not be in the jar.
Edit:
(A working) MWE: http://pastebin.com/CNq6zgPw
The ClassLoader class has two relevant methods:
getResource(path) delivers a URL for any resource on the classpath,
getResourceAsStream(path) delivers an input stream for the resource.
You can use these methods with overloads of the AudioSystem.getAudioInputStream(...) method to get an audio stream that reads a resource in your JAR file.
Note that if you call these methods on a ClassLoader object, that paths will be resolved in the namespaces of the JAR files on the classpath ... not the filesystem namespace of your development platform.
You can load any resources using this code from the jar or outside of the jar:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("~/src/package/name/assets/TestSound.wav");
This snippet of code worked for me:
Clip clip = null;
ClassLoader cl = this.getClass().getClassLoader();
AudioInputStream ais;
URL url = cl.getResource("com/example/project/assets/TestSound.wav");
System.out.println(url);
try {
ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
The important thing is not adding the /src/ folder to the class path.
The critical change is changing cl.getResource("/com/example/project/assets/TestSound.wav") to cl.getResource("com/example/project/assets/TestSound.wav");
because /com/... indicates that the path is absolute, whereas com/... indicates that the path is relative.
For example,
System.out.println(new File("/Test.File").getAbsolutePath());
System.out.println(new File("Test.File").getAbsolutePath());
return
/Test.File
/Users/alphadelta/Documents/Workspace/TestProject/Test.File
respectively.
The first File created is created using "/Test.File", which is absolute. The second is created using "Test.File", which is relative to the project root in eclipse.

File found in eclipse but not when I run the .jar in terminal

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
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)) {
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.

Categories