Audio not playing with JAR File - java

I created a project that plays audio within the netbeans IDE. Those audio files were placed in the Classes folder.
Although when I created it as a JAR file, it was unable to locate the audio files. I even copy and pasted the files inside the new dist folder.
Here is a snippet of code:
private void playSound39()
{
try
{
/**Sound player code from:
http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("./beep39.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Audio file not found!");
}
}

If you want to embedd the audio file in your program it's must be placed inside the src folder in a package.
For example I'll demonstrate a code I use to set icons to buttons (should work for audio files as well) :
While creating the JFrame I wrote :
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Icon/PatientBig.png")));
I have in my project a package called GUI with a subpackage called Icons where my icons exist and they all are in src folder.
When you using getClass().getResource function , I prefer to use an absolute path.
After seeing your respone I have noticed that you keep using . in the begining of the class path, I copied the snippet you published and removed the . from the begining of the path and placed my audio file bark.wav in the src folder in the default package and it worked
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
Then I placed the audio file inside a package called test1 and modified the path in getResourceAsStream function and again it worked:
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/test1/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
The Most important thing is to remove . from the path

try this
InputStream in = getClass().getResourceAsStream("/beep39.wav");

I think you need to bypass use of the InputStream. When running the getAudioInputStream method, using InputStream as a parameter triggers markability and resetability tests on the audio file. Audio files usually fail these tests. If you create your AudioInputStream with a URL or File parameter, these tests are circumvented. I prefer URL as it seems more robust and can "see into" jars.
URL url = getClass().getResource("./beep39.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
Then, in a while loop, you would execute a read method on the AudioInputStream and send the data to a SourceDataLine.
The Java Tutorials covers this in their audio trail. This link jumps into the middle of the tutorials.
AFAIK, there is no "AudioPlayer" in the Java 7 SDK.

Related

FIle Sound not found, and return java.lang.NullPointer Exception

I have tried putting the .wav file on the separate modules title sound, putting it in the same packages with the program, and putting it in src. I checked using command prompt and the file is playable. I also make sure that .wav is supported by Java. What I'm confused about is, it did not return FileNotFound exception, but NullPointer Exception. What is it that I am doing wrong? Beforehand, thank you for those who can help.
Here is my source code:
Clip brickCollisionSound;
Clip gameMusicSound;
Clip gameWinSound;
Clip paddleCollisionSound;
Clip wallCollisionSound;
private void initSounds() {
try {
File soundFile = new File("./gameOver.wav");
//URL url = this.getClass().getClassLoader().getResource("sound/gameOver.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
gameOverSound = AudioSystem.getClip();
gameOverSound.open(audioIn);
soundFile = new File("./BrickCollission.wav");
//url = this.getClass().getClassLoader().getResource("sound/BrickCollission.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
brickCollisionSound = AudioSystem.getClip();
brickCollisionSound.open(audioIn);
soundFile = new File("./gameMusic.wav");
//url = this.getClass().getClassLoader().getResource("sound/gameMusic.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
gameMusicSound = AudioSystem.getClip();
gameMusicSound.open(audioIn);
soundFile = new File("./gameWin.wav");
//url = this.getClass().getClassLoader().getResource("sound/gameWin.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
gameWinSound = AudioSystem.getClip();
gameWinSound.open(audioIn);
soundFile = new File("./PaddleCollision.wav");
//url = this.getClass().getClassLoader().getResource("sound/PaddleCollision.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
paddleCollisionSound = AudioSystem.getClip();
paddleCollisionSound.open(audioIn);
soundFile = new File("./WallCollision.wav");
//url = this.getClass().getClassLoader().getResource("sound/WallCollision.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
wallCollisionSound = AudioSystem.getClip();
wallCollisionSound.open(audioIn);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
}
}
public void playMusic() {
gameMusicSound.setMicrosecondPosition(0);
gameMusicSound.start();
gameMusicSound.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stopMusic() {
if (gameMusicSound.isRunning()) gameMusicSound.stop();
}
public void playGameOverSound() {
gameOverSound.setMicrosecondPosition(0);
gameOverSound.start();
}
public void playGameWinSound() {
gameWinSound.setMicrosecondPosition(0);
gameWinSound.start();
}
public void playBrickCollisionSound() {
brickCollisionSound.setMicrosecondPosition(0);
brickCollisionSound.start();
}
public void playPaddleCollisionSound() {
paddleCollisionSound.setMicrosecondPosition(0);
paddleCollisionSound.start();
}
public void playWallCollisionSound() {
wallCollisionSound.setMicrosecondPosition(0);
wallCollisionSound.start();
}
```
File soundFile = new File("./gameOver.wav");
this attempts to find that file in the 'current working directory'. What that is depends on the user, and thus, this isn't how you do that. Delete these lines.
URL url = this.getClass().getClassLoader().getResource("sound/gameOver.wav");
That's also not how you do that.
It's:
package com.foo;
class Foobar {
private void initSounds() {
Foobar.class.getResource("sounds/gameOver.wav");
}
}
This looks for a directory named sounds which should be in the same place that the file Foobar.class is in (even if it is in a jar or jmod file, that's fine). In other words, if you have a jar with that, you'd have com/foo/Foobar.class and com/foo/sounds/gameOver.wav in that jar file. If you prefer to from the root of the jar, you can do that: .getResource("/sounds/gameOver.wav") (note the leading slash) would look in the same jar/dir/etc. So if your Foobar.class is currently running from /Users/Khaela/workspace/game-project/bin/com/foo/Foobar.class, then the sounds file is looked for in /Users/Khaela/workspace/game-project/bin/sound/gameOver.wav.
Note that maven and most other build tools copy the files from src/main/resources over the same way that IDEs and tools compile files over from src/main/java. Thus, put them there (if using .getResource("sounds/gameOver.wav"), make sure src/main/resources/foo/bar/gameOver.wav exists). IDEs with maven plugins will figure it out and make it work, too.
} catch (UnsupportedAudioFileException | IOException | >LineUnavailableException e) {
}
This is incredibly silly code. Don't catch exceptions if you don't know what to do (unless you rethrow them), and definitely don't catch exceptions and completely ignore them. It's confused you so much it led you to asking questions on SO. Do not write catch blocks like this.
The right 'I dunno what to do!' catch block is this:
} catch (SomethingYouHaveNoClueAbout e) {
throw new RuntimeException("Uncaught", e);
}
This ends execution (you want that - bad things happened, don't just continue on blindly, with half of the code you ran so far not having done what you wanted it to do, and no idea which half or what failed - continuing on with code execution is a very bad idea under those circumstances, obviously) - and preserves ALL information about the problem (which is a lot: Message, exception type, stack trace, causal chain, suppressed list, and depending on the exception even more info).

My .jar file won't open MP3 files (I'm using Jlayer - JZoom library)

I did this small Java project that in it's turn opens different MP3 files. For that I downloaded the JLayer 1.0.1 library and added it to my project. I also added the MP3 files to a package on my project -as well as some JPG images- so as to obtain them from there, and I'm using a hashmap (mapa) and this method to get them:
public static String consiguePath (int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i)).getPath();
}
so as to avoid absolute paths.
When I open an MP3 file I do this:
try {
File archivo = new File(AppUtils.consiguePath(12));
FileInputStream fis = new FileInputStream(archivo);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
Player player = new Player(bis);
player.play();
} catch (JavaLayerException jle) {
}
} catch (IOException e) {
}
The whole thing runs perfectly in NetBeans, but when I build a .jar file and execute it it runs well but it won't open the MP3 files. What called my attention is that it doesn't have trouble in opening the JPG files that are on the same package.
After generating the .jar I checked the MyProject/build/classes/Movimiento folder and all of the MP3 files were actually there, so I don't know what may be happening.
I've seen others had this problem before but I haven't seen any satisfactory answer yet.
Thanks!
Change the consiguePath to return the resulting URL from getResource
public static URL consiguePath(int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i));
}
And then use it's InputStream to pass to the Player
try {
URL url = AppUtils.consiguePath(12);
Player player = new Player(url.openStream());
player.play();
} catch (JavaLayerException | IOException e) {
e.printStackTrace();
}
Equally, you could just use Class#getResourceAsStream
Resources are packaged into your Jar file and can no longer be treated as Files

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

No errors but no audio?

I put this right after I listed my imports, there are no errors but when I click run my interface shows up but there is no audio. I have the .wav file in the src directory and I've placed it in every folder once but still when I click run there is no audio. Assistance would be very appreciated.
public class Mygame extends javax.swing.JFrame {
private Clip music;
private void startSong(){
try{
AudioInputStream stream = AudioSystem.getAudioInputStream(getClass().getResource("gamemusic.wav"));
music = AudioSystem.getClip();
music.open(stream);
music.start();
}
catch(Exception e){
music = null;
}
}
If you are using netbeans then paste your wav file in Files tab beside project tab at left top corner.

Error Accessing Embedded Resource

I'm making a program, and I want it to start playing sounds when it opens. I figured the easiest way for me to do this is to embed the .wav file in the src folder in my jar. I have placed the file in a packaged called files and all the other files i am using such as pictures are in that package and they all work fine. my method for playing sounds is here:
public static void playSound(String dir, int loopTimes) throws Exception {
URL url = new File(dir).toURI().toURL();
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
if (loopTimes == -1)
loopTimes = Clip.LOOP_CONTINUOUSLY;
clip.loop(loopTimes);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
}
});
}
and it works for playing the sounds when they are on my desktop, my documents, anywhere else. the path that i am inputting for playing the sound is "files/FBP.wav" were FBP is the name of the file. i havent been able to find any solutions on google, and i have the feeling that it is because it is in the JAR. I have also just simply tried this:
if(new File("files/FBP.wav").exists()){
System.out.println("EXISTS!");
}
System.exit(0);
and it never printed out that it exists. i have made sure that it is in the bin folder as well. i am using eclipse. the error i get is filenotfoundexception. any help is appreciated! Thanks in advance!
Replace:
URL url = new File(dir).toURI().toURL();
With:
URL url = MySoundClassName.class.getClassLoader().getResource(dir);
Or for non-static methods:
URL url = getClass().getClassLoader().getResource(dir);

Categories