javafx will cannot locate my .wav or .mp3 files - java

I've been trying to play audio clips through Java and have had trouble using the javafx library. I've placed the sound files in my src folder and tried various ways of accessing them, and yet i get a NullPointerException each time I access them.
Media sound = new Media("file:beep.wav");
MediaPlayer player = new MediaPlayer(sound);
player.play();
Another way i tried to access the file was
File f = new File("beep.wav");
Media sound = new Media(f.toString());
Also tried a few other things. When i do the system.out.print checks all filenames and paths print out correctly
I am running this on Ubuntu (Wily) 15.10, using Eclipse (Kepler) if that may help anyone help me
Appreciate the help!

Do you run your program on text editing programs (NetBeans, Eclipse, etc) or tryingto run jar file?
In first case, try to place your audio file in your project folder. For example: C:/.../NetBeansProjects/MyPRoject/beep.wav , but declare it wihtout any folder names, like this
Something f = new Something("beep.wav"); // Something is not an Object XD
In second case, after clean-building place your audio file in dist folder of your project.
Let me know if it helps.

Yes, I tried that with no success.
I tried using the Clip method (shown below) and found that I encountered a memory error after playing a sound more than 20 times or so. after clearing out as much memory pertaining to the systems clip to fix the error i just decided it may be a driver issue since i was running on (32bit)Lubuntu and had to manually install a few drivers.
clip = AudioSystem.getClip(null);
clip.open(AudioSystem.getAudioInputStream(sound));
clip.start(); //Clip.stop somewhere down the line
I then installed the newest release of (64bit)Ubuntu and the clip method has worked perfectly for me since.
Should I be doing any cleanup when using this method to avoid memory problems, or will external programs take care of that for me?
Thank you for your timely response.

Put all your sound files in a folder called 'sounds'. The folder should be in your project folder at the same level as the src folder. Then call the following method that takes the audio file name as a String argument.
public void playSound (String musicFile){
Media sound = new Media(new File("sounds/" + musicFile).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.stop();
mediaPlayer.play();
}
playSound("do.wav")

Related

Generated .jar is unable to load some media files

I built a java program using IntelliJ. This program loads media files like an image (.jpg) and audio (.wav).
When i run my project inside of the IDE, it works fine.
But when i generate a .jar file of my project, the image and audio files will not load.
When i try to load the .wav audio file, i get a FileNotFoundException
When i try to load the .jpg file, i get an IIOException: Can't read the input file!
I'm loading the image like this:
image = ImageIO.read(ImageScreen.class.getResourceAsStream("/quiz/resources/images/image_1.jpg"));`
When i inspect the top of the stack trace in the debugger, i can see: javax.imageio.ImageIO.read(Unkown Source).
In other parts of my application, i'm able to load text files from a similar directory like this and it works in the .jar file too:
reader = new BufferedReader(
new InputStreamReader(
WordScreen.class.getResourceAsStream(
"/quiz/resources/words/wordlist.txt")));`
I only have one package called quiz in my project and i don't understand why this isn't working, as i am specifying an absolute path.
I've looked at other questions such as this one, but in my opinion, i'm doing what is being suggested.
Thank you everyone for your help. I have managed to find a fix for my problem.
I have changed this:
image = ImageIO.read(ImageScreen.class.getResourceAsStream("/quiz/resources/images/image_1.jpg"));
To this:
image = ImageIO.read(this.getClass().getResourceAsStream("/quiz/resources/images/image_1.jpg"));
I am now retrieving the .wav in the same way and it is working:
this.getClass().getResourceAsStream("/quiz/resources/audio/audio1.wav");
try with getClassLoader()
this.getClass().getClassLoader().getResourceAsStream...

JavaFx: Pathing and Getting audio files to work in my .jar

I'm currently making a small game in JavFx and am trying to play a sound when objects collide currently this is my implementation:
if (paddle.getBoundsInParent().intersects(circle.getBoundsInParent())) {
dx *= -1;
Media sound = new Media(getClass().getResource("/Audio/Paddle.m4a").toString());
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.play();
}
The audio files are stored in a source folder I made named "Audio" that is alongside the src and bin folders. My issue is that I cannot figure out the correct path for the audio files or how to extract them into a .jar using eclipse.
An easy way to solve this would be to put your media files in the default package.
Then switch the file path in your code to just the name of the file, so /audio/Paddle.mp4 becomes Paddle.mp4
Since you did not specify a path, java will look in the default package and find your media file.

(Java) Trouble going between URLs and files with a .jar file

I'm making a rather big program in java. It has lots of files, including images, audio, and text files. When I'm running from Eclipse, the code I use works fine. However, I always have trouble gaining access to them from a .jar file that's on its own.
I'll give you an example of how I'm coding this.
For the BufferedImage, I have it this way:
File bgImgFile = new File("images/nature.jpg");
BufferedImage bgImg = ImageIO.read(bgImgFile);
For the AudioInputStream, I have:
File soundFile = new File("audio/two.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
And for the text file, I have:
FileReader reader = new FileReader("scripts/0.txt");
This all works fine for when I'm in Eclipse. However, I'm thinking about what I'll want to do for distribution. I want to have a .jar file that can run anywhere, and doesn't need to be in the same directory as those folders containing the files. I've done this before and it's worked fine.
This is what I tried to do for the image:
URL bgFileUrl = MainClass.class.getClassLoader().getResource("images/nature.jpg");
File bgImgFile = new File(bgFileUrl.getFile());
BufferedImage bgImg = ImageIO.read(bgImgFile);
I did similar things for the audio and text file. However, even when I tried in different combinations of having the files themselves in the same directory, having a slash in front of the plain file name, etc., nothing worked. I want to be able to include these files in the .jar file so I don't have to run the .jar from that specific folder.
One thing I don't understand is that, when I opened up the .jar file made using my original code, the images, audio, and scripts folders were in there and they had my files. They were there. However, when I tried to run it, I got an IIOException ("Can't read input file!") and a NullPointerException, even though I was using the same code as before.
How do I make it so the files are included in the .jar file so it can run on its own?
Thanks for the help!
Can you try below code
URL audioFileUrl = MainClass.class.getClassLoader().getResource("audio/two.wav"");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(audioFileUrl);

Playing an MP3 in a jar with mp3spi

I'm working on a Java project in Eclipse IDE. I want to deploy the project into a jar-file. Getting the audio to run is the part I have diffictuly with. I'm using the mp3spi library by javazoom for playing mp3 files. ( http://www.javazoom.net/mp3spi/sources.html )
I implemented my AudioPlayer almost like the sample on the javazoom website. ( http://www.javazoom.net/mp3spi/documents.html )
I could post the lengthy code here again, but it's almost the same with the difference that my AudioPlayer extends Thread so it can play independently. (and it works just fine in the development environment)
The problem I have is that I just can't get it to run when I export the project into a jar. I found already many questions and suggestions to this topic and I tried most of it. Sadly I still don't have a working solution. I'm sure it's out there but at this point I might miss the forest for the trees.
All the required libraries (jl1.0.1.jar, tritonus_share.jar and mp3spi1.9.5.jar) are in my jar and added to the classpath.
The curcial point of the code seems to be AudioInputStream (at line 10 in the sample) which takes a File to be created.
1st attempt - the code like suggested on javazoom.net:
File file = new File("src/resources/audio/test.mp3");
AudioInputStream ain = AudioSystem.getAudioInputStream(file);
What happens is:
Eclipse IDE:
Works fine, the mp3 plays.
Exported jar-File:
Jar works but mp3 does not play.
Exported jar-File opend with windows console:
Jar works but mp3 does not play.
Error messages: at audio.AudioPlayer.run(AudioPlayer.java:40)
java.io.FileNotFoundException: src\resources\audio\test.mp3
So I can't use „File“ in a jar because I'm not dealing with a file in the file system but a file inside my jar.
2nd attempt
URL url = ClassLoader.getSystemResource("resources/audio/test.mp3");
AudioInputStream ain = AudioSystem.getAudioInputStream(url);
What happens is:
Eclipse IDE:
Works fine, the mp3 plays.
Exported jar-File:
Jar works but mp3 does not play.
Exported jar-File opend with windows console:
Jar works but mp3 does not play.
Error messages: javax.sound.sampled.UnsupportedAudioFileException:
could not get audio input stream from input URL
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at audio.AudioPlayer.run(AudioPlayer.java:40)
I can't get an AudioInputStream from a URL? I don't know. So let's get to ...
3rd and 4th attempt
Attempt 3:
BufferedInputStream myStream = new BufferedInputStream(getClass().getResourceAsStream("/resources/audio/test.mp3"));
AudioInputStream ain = AudioSystem.getAudioInputStream(myStream);
Attempt 4:
BufferedInputStream myStream = new BufferedInputStream(ClassLoader.getSystemResourceAsStream("resources/audio/test.mp3"));
AudioInputStream ain = AudioSystem.getAudioInputStream(myStream);
Again both with the result playing in Eclipse IDE but not in the jar.
Exported jar-File opend with windows console:
Jar works but mp3 does not play.
Error messages: javax.sound.sampled.UnsupportedAudioFileException:
could not get audio input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at audio.AudioPlayer.run(AudioPlayer.java:40)
I am really lost here. Any help would be much appreciated.
Related topics:
File path or file location for Java - new file()
Reading File In JAR using Relative Path
Java Audio Stream (mp3spi lib), UnsupportedAudioFileException
Jar with compressed music with java?
I used to export my project always as a jar and all images that I loaded in a similar manner would load properly while the audio file would not.
Now, that I tried to export my project as a runnable jar, it works just fine (attempt 4, maybe other attempts as well). The following question and answer explains the difference between jar and runnable jar.
Java Eclipse: Difference between exporting as a JAR and exporting as a Runnable JAR
How that manifest file impacts the proper loading of resources with
ClassLoader.getSystemResourceAsStream
is beyond me, but apparently it does.
Somebody might want to elaborate on those maifest files because I really can't. Or perhaps there are other differences between the export of a jar and a runnable jar.
Since I have a working solution I am done for now with this subject.

Java - .jar unexpected issue with Netbeans

First of all, I am aware of Stack Overflow (and any competent forum-like website) policy of "search first, ask last", and, doing my homework, I searched various sources to find a solution to my issue. That said, I, failing to find any suitable answers, was left no choice but to ask this problem personally.
I have somewhat moderate programming skills, especially regarding the Java language. I am working on this 2D game with the default Java SE JDK. More specifically JDK 7u4. In this project, we have a class that manages most I/O operations. One of its methods returns the path to a file:
public static URL load(String resource) {
return ZM.class.getResource(resource);
}
Now, this method works fine when running the project on Netbeans (version 7.1). However, when building and cleaning the project, the resulting .jar file does not seem to agree with its creator. When running the .jar on command line, the JVM caught a NullPointerException. It seemed that the file was not being able to be read inside the .jar. Following my programmers instinct, I started debugging the project. My first attempt was to check whether the load method was the faulty member. I ran some tests and obtained a couple of interesting results:
When running the application on Netbeans and with "ZM.class" as the methods argument, it returned:
/D:/Projects/GeometryZombiesMayhem/build/classes/geometryzombiesmayhem/ZM.class
But when running it from the .jar file, it returned:
file:/D:/Projects/GeometryZombiesMayhem/dist/GeometryZombiesMayhem.jar!/geometryzombiesmayhem/ZM.class
Naturally, I tried removing the initial file: string from it. No effect. Then I tried taking the exclamation mark from [...].jar![...]. Again, nothing. I tried removing all the possible permutations from the path. No luck.
Testing the method against the very own .jar file worked okay. Now, when I try to access the inside of the file, it doesn't let me. On earlier versions of this project it worked just fine. I am not really sure of what is going on. Any help is welcome.
Thank you in advance,
Renato
When loading resources from a jar file, I've always used a classLoader. Everything seems to work the same whether you run from within the IDE, launch the executable jar file or run the program from a web site using JNLP.
Try loading the resource this way instead:
try {
ClassLoader cl = ZM.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("images/programIcon.jpg"));
// do stuff with img.
}
catch(Exception failed) {
System.out.println(failed);
}
One more suggestion - you should create a separate folder for resources. In my example above, images is a folder inside of my src folder. This way it will automatically become part of the jar when I build it, but I am keeping resources separate from source code.
I suppose your problem is in loading an image from your jar file.
Here is how i do it
URL imageurl = Myclassanme.class.getResource("/test/Ergophobia.jpg");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
piclabel.setBounds(0,0,myPicture.getWidth(null),myPicture.getHeight(null));
This way I can get the Ergophobia.jpg file inside 'test' package.

Categories

Resources