Clean and build, but my audio file is gone - java

I have a little question, I am building an app with the swing builder in Netbeans(note: it is Java). In this app I use an audio file I put in the main project folder, but when I start the jar, the audio file is not working, as if it's not included.
Does anyone know how I can fix this?
Any help will be greatly appreciated,
Black Magic

make sure that you have audio files in folder with jar and that path is correct. I used this method to play sounds:
public static synchronized void playSound(final File file)
{
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
} catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
)
.start();
}
In code i play sound using: playSound(new File("sounds/noise.wav"));
So i place my folder with noise.wav in folder with *.jar and it all works.

Related

How To Play A Local Sound File

I want to make a program that plays sounds and displays png images onto the JFrame. I am trying to put the png and sound files (.wav) into the package that the class that's displaying it is in. I can't seem to get it working though. I've looked up many methods on how to do it, it every time they all pop up NullPointer errors. Or that it couldn't find the file, even though the file path specified was exactly where it was when I went into File Explorer. So if anyone can help me find a way to play music and display the picture (getting the png file and making it an ImageIcon), that would be great.
Here is java code
Play Button action Performed
private void play_btnActionPerformed(java.awt.event.ActionEvent evt) {
SetImage();
PlaySound();
}
Play audio
void PlaySound() {
try (InputStream in = getClass().getResourceAsStream("sam.wav")) {
InputStream bufferedInS = new BufferedInputStream(in);
try (AudioInputStream audioInS = AudioSystem.getAudioInputStream(bufferedInS)) {
Clip clip = AudioSystem.getClip();
clip.open(audioInS);
clip.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
set image
void SetImage() {
audio_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/player/player.png")));
}

Playing a wav file in Java after compiling it to JAR

so I am making a birthday present for a programmer friend of mine. I am not that good with code but I made a window + gif + sound. But once I test it on another PC the sound won't work anymore, but the JAR file is big enough to contain the WAV. PLease help me, I really want to make a nice birthday gift. Here is the Sound code + main
public static void play() {
try {
File file = new File("C:/Users/timma/IdeaProjects/BirthdayAshley/1" + ".wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
Thread.sleep(clip.getMicrosecondLength());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args){
JFrame jf = new JFrame ("Happy Birthday");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(617,345);
jf.add(new Birthday());
jf.setVisible(true);
jf.setResizable(false);
play();
}
If the WAV is inside a JAR, it can't be referenced via a file.
But you can open it via Class.getResourceAsStream(). Everything else should stay the same.
InputStream stream =
SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");
use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.
clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));

What is the easiest way to load and play sounds in a java application?

I'm relatively new to java (I took a 1 semester online class, so I know the basic structure of the language but my knowledge has lots of gaps). I'm trying to write a simple ear training application for a class in microtonal music I'm taking, and I obviously need to be able to play sound with this application. Looking on the web, a lot of the info I've found is out of date and I'm having trouble figuring out the APIs for Clip, Dataline, etc. (again, I'm new!) Is there a simple way to load sounds onto some kind of object (like an AudioClip maybe?) so they can be played back when necessary? If it's more complicated than that, I would appreciate being directed to resources that would help me figure how this process works.
You can use this method to play a audio clip using java application
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
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();
}
Here's another tutorial on java how to add audio clips. You can check this too Tutorial in playing sounds in Java
You will need to import the following:
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.FileNotFoundException;
I created a method for playing the audio clip, as shown below:
public static void myMusic() throws FileNotFoundException {
try {
File wavFile = new File(/*file path*/);
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(wavFile));
clip.start();
} catch (Exception e) {
System.out.println(e);
}
}
Let's say for example, if your audio clip's file name is music.wav, your file path may be:
File wavFile = new File("music.wav");
Finally, to play the audio clip, you will need to call the method.

Add sound to my basic 'Sound Adventure' game

How can I add sound to my basic 'Sound Adventure' game?
I am a beginner and I want to make a basic sound adventure game. (Yes you heard it right, Sound Adventure.)
I know basics of Java and I can code text adventures, but I don't know how Sound works in Java quite yet. I've seen tutorials over the internet and they don't seem to work.
I am ready to change the format of my sound. (It's currently .mp3)
Also, I am using JDK 7 with Eclipse Kepler. (If that helps.)
Here's my code so far:
package everything;
import java.util.Scanner;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class Main {
public static void main(String[] args) {
// Declarations
System.out.println("Please Enter Your Name To Start...");
Scanner temp = new Scanner(System.in);
String name = temp.nextLine();
System.out.println("Okay " + name + ", Let's Get Started!");
System.out.println("Press N To Start The Game...");
while(!"N".equals(temp.nextLine())){
System.out.println("I Asked For The Letter N, Was It So Hard? Try Again!");
}
}
}
There's literally tons of resources with a simple Google Search.
Using JavaFX Framework
Simply use an instance of AudioClip. This one is very suitable for just playing single short sounds.
AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();
Using Standard Java API
Standard Java API is a little more painful, I don't have any experience with it but this piece of code has 60+ Upvotes on this related question.
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
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();
}

Audio does not play in Jar but does in eclipse

Sound does not play when I run the JAR, but it does when I run it in eclipse.
Here is where I load the clips:
public void init(){
System.out.println("grabbing Music");
String currentDir = new File("").getAbsolutePath();
name=new File(currentDir+"\\music\\").list();
clip=new Clip[name.length];
soundFile=new File[name.length];
for(int x=0;x<name.length;x++){
System.out.println(currentDir+"\\music\\"+name[x]);
try {
soundFile[x]= new File(currentDir+"\\music\\"+name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile[x]);
DataLine.Info info= new DataLine.Info(Clip.class, sound.getFormat());
clip[x] = (Clip) AudioSystem.getLine(info);
clip[x].open(sound);
clip[x].addLineListener(new LineListener(){
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
I do not get any errors when running it in Eclipse. There should be no possibility of an invalid directory error, so what is wrong?
-When the jar is run in CMD i get no errors.
edit: I feel like I am loading the audio wrong, hence why I pasted the code I used to load the files in. In my searches I haven't seen anyone use File to load in a sound file. Wonder if that is the problem?
First thing that goes into my mind is that you didn't attached your sound library classes into your jar.
In order to run your current code, the folder music should be in the same folder the jar file is located in.
Another solution is to package your music folder inside the jar file and then change your code to:
InputStream is = getClass().getResourceAsStream("/music/" + name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(is);
How about-
Right click on your project in Eclipse. Then New -> Source Folder.
Name the source folder anything. e.g. music_src.
Copy or drag the entire music directory in music_src. Then make the jar.
File systems have a hard time looking into jars.
Try using URL instead. A URL can locate a location within a jar. This happens a lot with folks trying to access resources in jars for the first time.
Otherwise things look fine.

Categories

Resources