Sound will not play in JAR file - java

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

Related

java Audio file location

I am working on a game in Java and I have a class that reads an audio file as InputStream and then plays that file through AudioPlayer.
I keep getting a file not found exception.
I have tried placing the audio files in many different locations, and nothing has worked.
This is my class code:
public void play(String string,int sleep) throws IOException
{
//this part does not recognize file
try {
//System.out.println(System.getProperty());
AS = new AudioStream(new FileInputStream(string));
AD = AS.getData();
loop = new ContinuousAudioDataStream(AD);
}
catch(IOException error){
System.out.print(string +" file not found");
}
AP.start(loop);
}
I pass a string like ("audio/beginning.wav")
You are using a path that is relative to the working directory defined when your program runs.
If you are running the program from Eclipse, by default it's the root directory of your program (top-level folder of the program). So normally placing the file in program_folder/audio/beginning.wav should work.
However, the working directory can be changed in the Run Configuration that you are using in Eclipse to run the program: go to the tab Arguments, and you'll find Working directory.
To debug the problem, check the output of the following:
System.out.println(new File("").getAbsolutePath());
Another option is to use the absolute path of the file.

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.
Here's my code:
public static void main(String[] arg) {
File file = new File("file.txt"); //File I want to change to .java
File file2 = new File("file.java");
boolean success = file.renameTo(file2); //boolean to check if successful
if (success == true)
{
System.out.println("file extension change successful");
}else
{
System.out.println("File extension change failed");
}
}// main
It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.
FIXED:
THE CAUSE OF THE PROBLEM:
I had placed the file I wanted to change, file.txt, in the package folder inside my project folder. C:\Users\Acer\workspace\MyProjectName\src\MyPackageName. As a consequence the file could not be found by the system.
THE SOLUTION:
I simply moved the file, file.txt, into the main project folder; C:\Users\Acer\workspace\MyProjectName and this fixed the problem. When I run my program it returns
file extension change successful
.
Thank you all for your help. I really appreciate it.
The Source file i.e file.txt should exist in the mentioned path (in your case its should be inside the eclipse project folder) and no file with the destination file name i.e file.java should exist in the mentioned path.
After you execute your code it will give file extension change successful and file.txt will be gone, its content will be transferred to the file.java
The classic Java File API is pretty limited in a number of respects. In this case, you are getting no feedback as to why the move is failing.
My recommendation, if you are on Java 7, would be to switch to use the nio file functionality that was added in that version. Not only are you then making use of a newer, more robust API, but you should get better messaging as to why your copy is failing. Here is equivalent code to the code you posted.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MoveFile {
public static void main(String[] arg) {
Path file = Paths.get("file.txt"); //File I want to change to .java
Path file2 = Paths.get("file.java");
try {
Files.move(file, file2);
System.out.println("file extension change successful");
} catch (IOException e) {
System.out.println("File extension change failed: " + e.getMessage());
e.printStackTrace();
}
}
}
For awareness, Oracle provides a good reference page for converting legacy file code to the nio code.

How to get a Resource in Apache Brooklyn

I am trying to build my own entity, which is based on VanillaWindowsProcess. The idea is, after the installation of the windows Machine, to execute some powershell commands, which are in a file.
I tried something which I used a lot of times in another Java projects to get a resource:
private void runInstallationScript() {
List<String> lines;
try {
lines = FileUtils.readLines(
new File(TalendWindowsProcessWinRmDriver.class.getResource("/my/path/file.txt").getFile()),
"utf-8");
executePsScript(lines);
} catch (IOException e) {
LOG.error("Error reading the file: ", e);
}
}
But I'm always getting the following:
ava.io.FileNotFoundException: File 'file:/opt/workspace/incubator-brooklyn/usage/dist/target/brooklyn-dist/brooklyn/lib/dropins/myProject-0.0.1-SNAPSHOT.jar!/my/path/file.txt' does not exist
It is strange, because the file is in the jar in that path. I did a test (without Apache Brooklyn infrastructure) and it works, but the other way, it does not.
The project follows the Maven standard structure and the file itself is under, src/main/resources/my/path/file.txt
Is there something that is wrong? Or maybe there is another approach to get that file? Any help would be appreciated.
You cannot access a resource inside a jar as a File object. You need to use an InputStream (or an URL) to access it.
Since you are already using getResource, you should change the method FileUtils.readLines to accept an InputStream (or an URL) as input.
If you don't have access to the source code, you can write your own method or use Files.readAllLines for Java >= 7.

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.

Runnable jar runs fine with java -jar, but problems with double-click

I am using the eclipse IDE and I just exported my project using 'export->Runnable Jar'. In my code, I have loaded a map using
URL map1url = this.getClass().getResource("map01.txt");
and later
inputmap = new File(map1url.getFile());
and then scanned its data using
Scanner sc = null;
try {
sc = new Scanner(inputmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Now, when I package the map01.txt into the jar, and double click it, it runs, but can't find the map01.txt. When I use java -jar, it runs, but still can't find the map.
When I place map01.txt in the same directory as the jar file, but not actually in the jar, and then double-click it, it runs, but doesn't find the map. If I run it using java -jar it runs and loads the map. What is the cause of this problem? How can I fix it? And the map01.txt is the only resource that doesn't work. I have loaded many images that are placed into the jar file, and they all load and display fine. For the images I use
URL url = this.getClass().getResource("myImage.gif");
try {
BufferedImage myImage = ImageIO.read(url);
} catch (IOException e) {
}
Why do they work and not my map? How can I fix this so I can package ALL my resources into one jar and then double-click it to run?
When you say "new File(map1url.getFile())", you're ending up with a java.io.File that refers to a file in the current directory. If the file actually is in the current directory of the process (which will happen if the file in in the current directory of your shell and you use "java -jar", then this will work; otherwise, it won't.
Why not just use getResource().openStream() to read the map file?

Categories