Playing .wav continuously in java: Invalid Format Exception - java

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.

Related

Playing custom audio formats with audio stream

So I started working on a video game and I want to create a custom sound format.
Path file = Paths.get("C:", "Users", "Mariobro85", "Desktop", "test.wav");
public void playFile() throws InterruptedException{
try{
File f = new File(file.toString());
URL url = f.toURI().toURL();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(15000);
}
catch(UnsupportedAudioFileException uafE){
System.out.println("ERROR: Audio data of the file " + file + " is not in wave format.");
}
catch(IOException ioE){
System.out.println("ERROR: Audio data of the file " + file + " is corrupted.");
}
catch(LineUnavailableException luE){
System.out.println(luE);
}
}
But this only plays standard .wav files.
I use wav in the custom format too, but the problem is that the audio data in my file starts at 0x60 instead of 0x0 and also there is information stored for loops, volume etc. Because of that it always throws an UnsupportedAudioFileException.
Is there any way to tell the AudioStream to jump to a specific address or is that not possible with standard java libraries?
If you want to edit the audio data before it is parsed by the default audio parser, you can edit it as follows
File file=new File("path/to/file");
byte[] bytes= Files.readAllBytes(file.toPath());
//edit or trim bytes as you wish.
ByteArrayInputStream inputStream=new ByteArrayInputStream(bytes);//you can even give an offset in this constructor
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputStream);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(xAmount);
If your format is truly custom, I recommend just following one of these standardised approaches and simply adding a header or footer to your byte array. No need to remake what has been done. Or, to make things simpler, you can just add a separate file you also load which has different data you wish to load with the audio.

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.

Java Sound .WAV format

I know this question has been asked a few times now about sound, and believe me, I have looked through to try and work out my own answer. I had the sound in Java working before on a different project without any difficulties using this:
public void playWelcome (){
try{
InputStream inputStream =
getClass().getResourceAsStream("Start.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}catch(IOException ioException){
ioException.printStackTrace();
System.out.println("Unable to Find WAV/Start FIle");
}
}
Obviously, this is not working before as explained so I have tried to use:
public void uploadDownload() {
try {
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(new
File("/DaWord/src/resources/upload.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
NOTE: I have tried the file without the slashes too. e.g. 'my file.wav'
Can someone help me out a bit here?
UPDATE:
So I have managed to get it going.. sort of:
File soundFile = new File("/Users/myname/DaWord/src/testing.wav");
AudioInputStream audioIn =
AudioSystem.getAudioInputStream(soundFile);
// 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();
But does anyone know how to do this by not providing the absolute path?? I have tried to use the .absoulutePath(); on the end of File such as : File
file = new File ("sound.wav").absouloutePath();
As explained here this are the ways to allocate a AudioInputStream piped from a file or URL,:
// from a wave File
File soundFile = new File("eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// from a URL
URL url = new URL("http://www.zzz.com/eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// can read from a disk file and also a file contained inside a JAR (used for distribution)
// recommended
URL url = this.getClass().getClassLoader().getResource("eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
This worked for the time being... with full path
File soundFile = new File("/Users/mrBerns/NetBeansProjects/DaWord/src/ching.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// 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();

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.

How can I play a WAV file using 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.

Categories