Im trying to play an mp3 but it throws UnsupportedAudioFileException
import javax.sound.sampled.*;
import java.io.*;
public class mp3play{
public static void main(String args[]) throws IOException{
File file = new File("clip.mp3");
AudioFileFormat baseFileFormat = null;
AudioFormat baseFormat = null;
try{
baseFileFormat = AudioSystem.getAudioFileFormat(file); // <---------- here
} catch(UnsupportedAudioFileException ex){
System.out.println("Audio File not Supported");
}
baseFormat = baseFileFormat.getFormat();
AudioFileFormat.Type type = baseFileFormat.getType();
float frequency = baseFormat.getSampleRate();
AudioInputStream in=null;
try{
in= AudioSystem.getAudioInputStream(file);
} catch(UnsupportedAudioFileException ex){}
AudioInputStream din = null;
baseFormat = in.getFormat();
AudioFormat decodedFormat =
new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
try{
rawplay(decodedFormat, din);
} catch(LineUnavailableException ex){}
in.close();
}
private static void rawplay(AudioFormat targetFormat,AudioInputStream din)
throws IOException, LineUnavailableException{
byte[] data = new byte[4096];
SourceDataLine line = getLine(targetFormat);
if (line != null){
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1){
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
nBytesWritten = line.write(data, 0, nBytesRead);
}
line.drain();
line.stop();
line.close();
din.close();
}
}
private static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException{
SourceDataLine res = null;
DataLine.Info info =
new DataLine.Info(SourceDataLine.class, audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
}
Here is the source and the clip: http://www.mediafire.com/?ecvm4ldfmz9