How can I play a WAV file using Java? - java

I send WAV files using a client and server, but I want to play the WAV when it received. I try this method but it did not work:
Runtime.getRuntime().exec("C:\\Documents and Settings\\Administratore\\Desktop\\gradpro\\test1\\s1.wav") ;
This the exception that I get:
"Error! It didn't work! java.io.IOException: Cannot run program "C:\Documents": CreateProcess error=193, %1 is not a valid Win32 application"
What am I doing wrong?

You need to execute the audio player program (probably windows media player or something similar) and then pass the filename (the full path to the file) in as a parameter:
String wavPlayer = "/path/to/winmediaplayer.exe";
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(wavPlayer, new String[]{fileToPlay}) ;
That should work.

What's wrong with Javas built in WAV playback support? You can play it back using AudioClip:
private void playBackClip(String fileName) {
try {
AudioInputStream soundStream = null;
if (fileName.startsWith("res:")) {
soundStream = AudioSystem.getAudioInputStream(
Object.class.getResourceAsStream(fileName.substring(4)));
} else {
File audioFile = resMap.get(fileName);
soundStream = AudioSystem.getAudioInputStream(audioFile);
}
AudioFormat streamFormat = soundStream.getFormat();
DataLine.Info clipInfo = new DataLine.Info(Clip.class,
streamFormat);
Clip clip = (Clip) AudioSystem.getLine(clipInfo);
soundClip = clip;
clip.open(soundStream);
clip.setLoopPoints(0, -1);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}

Is the use of the default audio player mandatory?
If not you might want to look into Java's AudioSystem.

Instead of specifying the media player to use, let windows look it up for you:
String comspec = System.getenv().get("ComSpec");
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(comspec, new String[]{"/c", "start", fileToPlay}) ;
You are basically doing something like:
cmd.exe /c start path_to_wav_file.wav
To see all the options start gives you (start is a built-in operation of cmd.exe, not a stand-alone program, which is why you have to run cmd.exe instead of a 'start.exe'), do
start /h

Old question, but for the record:
java.awt.Desktop.getDesktop().open(new java.io.File(my_filename));

Try:
Runtime.getRuntime().exec("'C:\Documents and Settings\Administratore\Desktop\gradpro\test1\s1.wav'") ;
Note the extra single quotations. I'm not even sure if your method will work, but give that a go.

Related

When Grabbing a File through JFileChooser why does this fail?

I'm trying to understand Java Swing GUIs. So I created a simple GUI to select a File.
When I attempt to use the FFMPEG wrapper to get file information I get the following error.
java.io.IOException: Cannot run program "C:\File.mp4": CreateProcess error=193, %1 is not a valid Win32 application.
I feel like I'm missing something minor here.
Thanks.
JFileChooser fc = new JFileChooser();
int nReturnVal = fc.showOpenDialog(jPanel1);
File fVideo = null;
try {
if (nReturnVal == JFileChooser.APPROVE_OPTION) {
fVideo = fc.getSelectedFile();
//Now you have your file to do whatever you want to do
jPath.setText(fVideo.getAbsolutePath());
FFprobe ffprobe = new FFprobe(fVideo.getAbsoluteFile().toString());
FFmpegProbeResult probeResult = ffprobe.probe(fVideo.getAbsolutePath());
FFmpegFormat format = probeResult.getFormat();
System.out.format("%nFile: '%s' ; Format: '%s' ; Duration: %.3fs",
format.filename,
format.format_long_name,
format.duration);
jEndTime.setText("" + format.duration);
} else {
//User did not choose a valid file
}
}
catch (Exception ex) {
System.out.println(ex.toString());
}

Java SoundSystem error

I am trying to make a program that plays sound back to you. How I got the sound was I went to this link and I had it speak some words for about 9 seconds. While he was speaking, I was recording him with Audacity. It recorded him at 16-bit PCM, 48 khz and a stereo channel.
The code I use to play the sound is,
public void playSound(String Path) {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Variables.class.getResourceAsStream("/com/project/resources/" + Path));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
and the error that pops up is at this link.
I have stored the file in another package located at com.project.resources.
If you have any questions about this situation, let me know.

I can't delete a file because it seems 'open'

I'm coding something with an audio part with WAV Files and after 2 days of searching for a bug, I really don't know where the problem is. I guess my thread doesn't stop and that prevents me from deleting a file, but when I'm debugging everything goes well and I've no exceptions or errors.
Here is my interface:
Picture of my interface
So when I want to delete a file by clicking on delete button that launches 'DeleteTrack' method and it works, but when I listen to it first thanks to listen button that launches 'PlaySound' method, I can't delete it, it's like if nothing happen.
Also, when I use 'PlaySound' and then I try to delete my file from windows I have this:
Windows error
Thank you for reading and I'll be very grateful if you could help me and sorry if my English isn't perfect.
GatherFiles method just return my list of waves I've verified it's not null
MajListAudio method refresh my list if I add or delete a song
public void DeleteTrack() {
String song_name = audioList.getSelectedValue();
File[] listeOfFiles = GatherFiles(null);
// Loop to find the file to delete and then delete it.
for(int i=0;i<listeOfFiles.length;i++){
if(song_name.equals(listeOfFiles[i].getName())){
listeOfFiles[i].delete();
}
}
// Refresh the list
MajListAudio();
}
}
So here is the function when I guess there is a problem.
public void PlaySound(File sound){
thread = new Thread(){
#Override public void run(){
try {
// Initialize a clip with our sound file
AudioInputStream audioStream = AudioSystem.getAudioInputStream(sound);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
// Variable that will updated to fix the percentage of the progressBar
int progressContains =0;
// Size in Seconds of our music
int sizeAudio = (int) (clip.getMicrosecondLength()/1000000);
clip.start();
do{
// indice allow us to know how much the progress bar has to grow every second. We divide with 100 because it's the maximum
//of the bar
int indice = 100/sizeAudio;
// Refresh the value of the bar and prepare her next value
progressBar.setValue(progressContains);
progressContains+= indice;
// The main thread is sleeping for 1s
Thread.sleep(1000);
}while(clip.isActive());
//Reset the bar after a play
clip.stop();
clip.close();
audioStream.close();
progressBar.setValue(0);
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
Others functions
public File[] GatherFiles(DefaultListModel myModel){
// If you want to get the list without implementing the model
if(myModel == null){
File[] both = Concatenate(getListOfFiles("\\cryptedAudio"), getListOfFiles("\\audio"));
return both;
// Same with a model
}else{
audioList.setModel(myModel);
File[] both = Concatenate(getListOfFiles("\\cryptedAudio"), getListOfFiles("\\audio"));
return both;
}
}
public File[] getListOfFiles(String endPath){
String folderPath = new File(".").getAbsolutePath();
folderPath= folderPath.substring(0, folderPath.length()-1);
File folder = new File(folderPath+endPath);
File[] listeOfFiles = folder.listFiles();
return listeOfFiles;
}
/*
*Return a new Array that contains borh arrays in parameters
*/
public <T> T[] Concatenate (T[] a, T[] b) {
int aLen = a.length;
int bLen = b.length;
#SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen+bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
I really suspect your threading is an issue. You wait one second after the sound finishes, at the very least. So maybe your delete happens too soon. One way around this, is to read everything from the file, and then make the sound. That way the file should always be closed.
byte[] bytes = Files.readAllBytes(sound.toPath());
AudioInputStream audioStream = AudioSystem.getAudioInputStream(
new ByteArrayInputStream(bytes)
);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
Since your problem appears to be your file not getting released to the system, we use File.readAllbytes which reads the whole file, and release it back to the OS before you even play a sound.
The concept behind your original setup should work, but it appears that your loop does not finish before you try and delete the file. It could also be that you start more than one thread to access the file.
Have you tried something like
AudioInputStream audioStream = AudioSystem.getAudioInputStream(sound);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
// play the audio...
clip.close();
audioStream.close();
This is just making sure that the AudioInputStream is getting closed properly since I'm not sure that clip.close() is closing it (though one would think it should...)
This method API AudioSystem.getAudioInputStream(sound) returns an AudioInputStream that you should close.
So better if you first assign the returned value to a local variable:
AudioInputStream inputAudioStream = AudioSystem.getAudioInputStream(sound);
And then you can open it using the clip instance:
Clip clip = AudioSystem.getClip();
clip.open(inputAudioStream);
Finally don't forget to close the inputAudioStream variable:
clip.close();
inputAudioStream.close();
I strongly suggest to use the try-with-resources Statement
try(AudioInputStream inputAudioStream = AudioSystem.getAudioInputStream(sound)) {
// Initialize a clip with our sound file
Clip clip = AudioSystem.getClip();
clip.open(inputAudioStream);
[.... ] your code
clip.close();
progressBar.setValue(0);
}
[.... ] your catch code

Playing .wav continuously in java: Invalid Format Exception

I want to play a .wav file continuously in Java. I found some code, but I can't make it work.
String fileName = "res/sound/buz.wav";
File file = new File(fileName);
AudioInputStream ais;
try {
Clip clip = AudioSystem.getClip();
ais = AudioSystem.getAudioInputStream(file);
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException e) {
e.printStackTrace();
}
I get an Invalid Format Exception on clip.open(ais):
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
at launcher.Launcher.main(Launcher.java:59)
I checked and file is created correctly and exists. So, what is the problem with my code?
If it matters, I'm working on Linux, but this should work on both Linux and Windows...
So I found a solution
try{
File file = new File (fileName);
AudioClip clip = Applet.newAudioClip(file.toURL());
clip.loop();
clip.stop();
}
catch(Exception e){
e.printStackTrace();
}
I can play a .wav file in a loop and stop it. That's what I wanted. And the code is very short.

Java - Unsupported Audio File Exception [duplicate]

This question already has an answer here:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file when loading wav file
(1 answer)
Closed 4 years ago.
I'm trying to add sound to my java game...
I'm playing Sultans of swing at runtime:
static String WHOOSH = "res/WHOOSH.WAV";
static String SULTANS = "res/DireStraits_SultansOfSwing.wav";
music(SULTANS, true);
And this whoosh sound when the ball hits a paddle
music(WHOOSH, false);
public void music(String path, Boolean loop) {
try {
//will go into file folder and get music file (getResource)
AudioInputStream audio = AudioSystem.getAudioInputStream(GamePanel.class.getResource(path));
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
if (loop) {
clip.loop(1000);
}
}
catch (Exception e) {
System.out.println("Check: " + path + "\n");
e.printStackTrace();
}
}
Problem:
The "Whoosh" always works, but Sultans of Swing does not. Sultans gives me this "Unsupported Audio File Exception" error, which oracle docs tells me
An UnsupportedAudioFileException is an exception indicating that an operation failed because a file did not contain valid data of a recognized file type and format.
Error:
Check: res/DireStraits_SultansOfSwing.wav
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
But you can see from these photos that they're both .wav files...
Why is it throwing that error? Is it a size issue?
Thanks!
When I've used wav files for a game, I've done something like this (I've updated it with your path):
public void endingSound() throws IOException{
ClassLoader cl = this.getClass().getClassLoader();
InputStream failSound = cl.getResourceAsStream("res/DireStraits_SultansOfSwing.wav");
if (failSound != null){
AudioStream as = new AudioStream(failSound);
AudioPlayer.player.start(as);
}
else{
System.err.println("cannot load ending sound");
}
}
In this way I assure you won't have any problems when you will export as jar. If is still doesn't work try to rename or replace that file; it may be corrupted as #MadProgrammer said.

Categories