Reputation: 1168
I am currently having trouble playing around with the javax.sound.sampled
library. Here's the MCV code that I use to play my audio files:
import javax.sound.sampled.*;
import java.io.File;
public class Foo
{
public static void main(String[] args)
{
try
{
File f = new File("alarm.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(f);
Clip clip = AudioSystem.getClip();
clip.open(ais);
clip.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This code will sometimes throw an UnsupportedAudioFileException
.
Basically, I have 5 .WAV files that I know are uncorrupted because they play perfectly fine when I open them in my music playing software. However, the Java program only works with 3 of them.
Oracle mentions support for this file format here. How can I make sure that all of my .WAV files are compatible with Java's audio API? Is there a foolproof way of playing .WAV files if for some reason they do not have the appropriate encoding?
Upvotes: 1
Views: 2741
Reputation: 37875
You can use the following code to get a list of the supported formats for playback:
public static List<AudioFormat> getSupportedAudioFormats() {
List<AudioFormat> result = new ArrayList<>();
for (Line.Info info : AudioSystem.getSourceLineInfo(
new Line.Info(SourceDataLine.class))) {
if (info instanceof SourceDataLine.Info) {
Collections.addAll(result, ((SourceDataLine.Info) info).getFormats());
}
}
return result;
}
AudioFormat.Encoding
lists the encodings supported by javax.sound.sampled
.
A safe WAV audio format is 16-bit PCM at 44100Hz.
You can discover the format of a particular file with:
File file = new File("path_to_file.wav");
AudioFormat fmt = AudioSystem.getAudioFileFormat(file).getFormat();
This will be a little more lenient than trying to get a line for example, but it will still throw if the WAV file has e.g. mp3 data. A WAV file is a container that can store encodings beyond PCM, some of which javax.sound.sampled
does not normally support.
Upvotes: 5
Reputation: 1781
If you look up UnsupportedAudioFileException, you'll notice that it is thrown when a file is either of an unsupported type, or of an unsupported format. The format is what's getting you.
Java Sound is capable of a variety of different formats, but which ones specifically are generally system dependent. You can find out which formats are supported with:
DataLine.Info.getFormats();
This method returns an array of AudioFormat objects, each of which describes an audio language that your Java implementation can speak.
Given that you can play the files on other players, it is likely that some part of your system is perfectly capable of understanding each of the wav formats; but you might consider checking on which data line it is being fed through, as that hardly means that they are universally supported.
Upvotes: 0