my program run 100% from compiler put not run 100% from dist - java

my java progeam run 100% if i run it from the compiler netbeans put if i run it from file manager its will be in dist folder inside the project (the program have a button that run wav file) the button have a catch ioexception if i run it from compiler the sound will run put if i run it from dist folder or move then run it to any path the catch that have the ioexception as a parameter will excecute i used audioSystem and cought it with a Clip class so if any exception occure in the first way the Clip class will try to run the sound file. code:
public void getSoundData(int delay){
ActionListener taskPerformer = new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
try{
int random=(int)(Math.random()*12+1);
InputStream input = new FileInputStream("src/azcar/sounds/"+String.valueOf(random)+".wav");
AudioStream audio = new AudioStream(input);
AudioPlayer.player.start(audio);
} catch (Exception exc) {
try {
Clip clip = AudioSystem.getClip();
int random=(int)(Math.random()*12+1);
AudioInputStream input = AudioSystem.getAudioInputStream(new File("src/azcar/sounds/"+String.valueOf(random)+".wav"));
clip.open(input);
clip.start();
} catch (LineUnavailableException ex) {
JOptionPane.showMessageDialog(null, ex);
} catch (UnsupportedAudioFileException ex) {
JOptionPane.showMessageDialog(null, "نوع ملفات الصوت غير مدعوم");
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "لم أتمكن من االوصول لملفات الصوت");
}
}
}
};
Timer timer = new Timer(delay*1000*60,taskPerformer);
timer.setRepeats(true);
timer.start();
}

In the above you are using the relative path to look up you wav file. From the root folder of the project you will read 'src/azcar/sounds/.wav', but from the dist folder you are effectively reading from 'dist/src/azcar/sounds/.wav'.
You can start to test this by entering the absolute path to the folder as a first step. After that you can then move to passing in a sound folder path as a variable to your application.

Related

Needing to type full path to save file?

Okay, this is my first post here, sorry if i did something wrong. (please let me know if i did aswell)
So i've been trying to make a "data" folder with a audio(.wav) file in it when the runnable jar file is run but for some reason it doesn't work, i've tried to get this working for the last week but i finally kinda gave up on trying to get it working without help(other than searching around the internet) and therefore ask here.
So i have this code:
public static void loop(String path, int volume) {
try {
if (volume > 6) throw new IllegalArgumentException("Requested volume ("+volume+") is higher than allowed. (maximum 6)");
else if (volume < -80) throw new IllegalArgumentException("Requested volume ("+volume+") is lower than allowed. (minimum -80)");
else {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(path)));
clip.loop(Clip.LOOP_CONTINUOUSLY);
FloatControl gain = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gain.setValue(volume);
clip.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
for looping a .wav file continuously and it works, then i try to save the file with this code:
public void save(String music, String output) {
try {
File sound = new File(music);
AudioInputStream ais = AudioSystem.getAudioInputStream(sound);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(output));
} catch (IOException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
And that seems to work aswell when i do something like this:
save("D:\\Eclipse\\eclipse\\workspace\\Test\\data\\music.wav", "C:\\Users\\Karim\\Desktop\\data\\test.wav");
loop("C:\\Users\\Karim\\Desktop\\data\\test.wav", -30);
But if i try to do this instead:
private File jar() {
try {
File jar = new File(Game.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
return jar;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
private File data = new File(jar().getParentFile().getPath()+File.separator+"\\data");
private File music = new File(data.getPath()+"\\music.wav");
save(music.getPath(), "C:\\Users\\Karim\\Desktop\\data\\test.wav");
loop("C:\\Users\\Karim\\Desktop\\data\\test.wav", -30);
it won't save the file, why is that and what can i do to make it save?
Final Notes:
I'm pretty new to java.
I'm pretty new to programming in itself.
I don't want to use a library, i wanna try to make it work without and i'm so close.
If i forgot to say anything please let me know and i'll edit this post or make a comment.
EDIT: Just wanted to make it clear that this works in the IDE but not when i export it. Also i have the data folder both IN the 'src' folder and beside the 'src' folder, just for testing.

.wav sounds not playing in Java

I am currently using this function to play .WAV files
public void playSound(String sound){
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource(sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
The problem is that no sound is being played when I call the function on a file, no errors or exceptions are thrown or whatsoever the program just starts and stops, no sound plays, I tried with a lot of different .WAV files with no success.
The programm stops before it has time to play the sound since start is non-blocking.
Try the following :
clip.start();
clip.drain();
clip.close();
This works for me:
public void sound() {
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("./sounds/player-laser.wav"));
Clip test = AudioSystem.getClip();
test.open(ais);
test.loop(0);
}catch(Exception ex){
ex.printStackTrace();
}
}

how to include sound in java

i have made a jar program that need to run an audio file
this is how i open the audio file(not in jar file)
Thread sound = new Thread(){
public void run(){
MakeSound.playSound("Raef.wav");
}
};
i run it with
sound.start();
and end it with
sound.stop();
when i run it on blue j its worked but the sound isnt play on the jar files
can someone solve this ?
i need to make a program with jar
nb : MakeSound is another class i used to play the sound
public class MakeSound {
private static final int BUFFER_SIZE = 128000;
private static File soundFile;
private static AudioInputStream audioStream;
private static AudioFormat audioFormat;
private static SourceDataLine sourceLine;
/**
* #param filename the name of the file that is going to be played
*/
public static void playSound(String filename){
String strFilename = filename;
// buka file
try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
#SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
The exact steps to put an audio file in a jar depends on the IDE you are using.
What I normally do is to make a subfolder "audio" and put the audio files there. The subfolder is a subfolder of the code source.
Then, in the code, I create a URL that points to this subfolder.
URL url = this.getClass().getResource("audio/" + fileName);
I don't know about the specifics of MakeSound.playSound(). Hopefully it accepts a URL as a parameter. If it only accepts file names, you might need to rewrite it. Operating Systems generally aren't set up to find files that are packed in jars. URLs, though, are able to point inside of a jar.
Key point: the calling code is in a folder. I used "this" instead of invoking the class name of the calling code which is also possible. If this folder has a subfolder named "audio", the above line of code should find the file.

Can I call a .mp3 or .wav file from a Java package in NetBeans? [duplicate]

This question already has answers here:
How to read a file from jar in Java?
(6 answers)
Closed 8 years ago.
My friend asked me to create an app that he can use in conjunction with the game Plague Inc, and he wants the soundtrack from the game to play in the application. Upon doing web research I have tried everything and nothing works. Is it possible to call the soundtrack from a java package (like with an image) instead of specifying folder directories and URLs? There was some promising information I found online but when I ran the code after trying it, the AudioInputStream keeps on giving me errors. I have tried using the clauses exceptions but that severely conflicted with the main method and the application would not even run. I have tried putting the coding in the constructor, a new method and even in the main method itself but all of them just throw out errors when I run the application (I don't even know where to put it so that it will work). Please help as this is getting seriously frustrating.
My package is called Sound and the file is called plague.wav
And although the game is an Android game, my application runs off Windows PC
Here is the coding I have so far:
File sound = new File("/Sound/plague.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (LineUnavailableException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedAudioFileException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
}
You can get it as a resource stream
Check this:
InputStream input = getClass().getResourceAsStream("/Sound/plague.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (LineUnavailableException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedAudioFileException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
}
Here's a sample class:
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class Snippet {
public static void main(String[] args) throws Exception {
try {
InputStream input = Snippet.class.getResource("/Sound/sound.wav")
.openStream();
AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

No sound after export to jar

I have problem with my app. When I run app in Eclipse, sound played well, but if I export app to runnable jar, sound doesn't work.
Method, where sound is played:
public static synchronized void playSound()
{
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(getClass().getResourceAsStream("sound.wav"));
clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}).start();
}
Where can be a mistake?
The problem is in this
AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("sound.wav"));
in JAR file isn't working getResourceAsStream for any reason. So I replace it with getResource:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getResource("sound.wav"));
and this works fine.

Categories