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

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.

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

Relative path's to images and sound in Java

Currently the project that I am making is game made with Jframe/Jpanel. I am using imports of images and sound through:
images:
ImageIcon a = new ImageIcon("C:/Users/Home/IdeaProjects/Game/src/DragonRoll/sprites/user_sprite_down.png");
player = a.getImage();
//sign
Sound:
String gongFile = ("C:/Users/Home/IdeaProjects/Game/src/DragonRoll/music/game_track.wav");
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
The images and the soundtrack from the example is seen to be imported from a direct path not a relative one meaning that it does not work on other computer or devices since they do not have the exact same path. Can someone recommend any solutions to this, please provide example code. I have tried just removing the path except the folder which contains the images and the image name itself but that did not work.
I am using Intellij and running as an executable java file.
Also the folder which contains all of the project goes like:
- Main project folder
- Branches into .idea, out and src
- src contains classes of the game and 2 folders called images and music
By convention source files in a Java project (everything that ends with .java) should be in a folder called src/main/java. Resources such as images, audio files, default config files, etc. are usually placed in a second source folder called src/main/resources. This way the compiled sources (i.e. the .class files) and the resource files will be on the classpath at run time of your application.
To load for example the src/main/resources/DragonRole/music/game_track.wav resource from your classpath you can simply do this:
InputStream gameTrackIn = MyClass.class.getResourceAsStream(
"/DragonRole/music/game_track.wav");
To load the src/main/resources/DragonRoll/sprites/user_sprite_down.png resource from your classpath you can simply do this:
ImageIcon userSpriteDownImg = new ImageIcon(MyClass.class.getResource(
"/DragonRoll/sprites/user_sprite_down.png"));
Your project structure should look like this:
Game (project root)
└ src/main
├ java (source root)
└ resources (resource root)
Basing on your comment responses, I propose you to place your resource files inside the jar.
After, Accessing to a resource file can be done in a such way : YourClass.class.getResource("sun.png") if the file is at the correct place.
Your main task now is placing the resource files to the convenient place and ensuring that you build allows to create the JAR with the expected files in the expected directory.
You don't seem to use Maven. It is not a prerequisite but it could easy your work to create the jar.
It's a common question. You should find some good examples about it.
Ended up using:
ImageIcon c = new ImageIcon("src/main/resources/sprites/new_background_panel.png");
Meaning it was looking from the source folder and not the whole computers path, thanks all others who helped out.

javafx will cannot locate my .wav or .mp3 files

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")

In netbeans, how to save or access an image after deploying jar file

I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds

Java - Audio URL

I have a audio file stored in a folder within the project and I'm trying to call the sound file within the folder.
I am able to call the file using the full URL
new java.net.URL("file:C:\NetBeansProjects\Puzzle\audio\applause2.wav"));
But is there a way to shorten it so that if I move the project I don't require changing the code?
Thanks
File file = new File("audio\applause2.wav");
Assuming you keep the audio folder at the same level relative to the jar

Categories

Resources