/***
* MP3播放器实现
* 线程不安全,没有必要多个线程去启动播放器
*
*
*@authorLee Jones*/publicclassMp3PlayerimplementsAudioPlayer {privatestaticfinalLog log=LogFactory.getLog(Mp3Player.class);privatestaticfinalbyte[] AUDIO_BUFER=newbyte[4096];privateAudioInputStream audioStream;privateAudioFormat decodedFormat;privateAudioInputStream decodedAudioStream;
@Overridepublicvoidplay(InputStream input) {if(input==null) {
log.warn("input stream is null");return;
}try{
init(input);
play();
}catch(Exception e) {
log.error("play error:", e);
}
}
@Overridepublicvoidplay(File file) {if(file==null) {
log.warn("audio file is null");return;
}try{
play(newFileInputStream(file));
}catch(FileNotFoundException e) {
log.error("file to inputStream error:", e);
}
}
@Overridepublicvoidplay(URL url) {if(url==null) {
log.warn("url is null");return;
}try{
play(url.openStream());
}catch(IOException e) {
log.error("url open inputStream error:", e);
}
}/*** init
*
*@paraminput
*@throwsUnsupportedAudioFileException
*@throwsIOException*/protectedvoidinit(InputStream input)throwsUnsupportedAudioFileException, IOException {
initAudioStream(input);
initDecodedFormat();
initDecodedAudioStream();
}/*** init audio input stream
*
*@paraminput:audio input stream
*@throwsIOException
*@throwsUnsupportedAudioFileException*/protectedvoidinitAudioStream(InputStream input)throwsUnsupportedAudioFileException, IOException {
audioStream=AudioSystem.getAudioInputStream(input);
}/*** init decoded format
*
*@throwsUnsupportedAudioFileException
*@throwsIOException*/protectedvoidinitDecodedFormat()throwsUnsupportedAudioFileException, IOException {
AudioFormat baseFormat=audioStream.getFormat();
decodedFormat=newAudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(),16,
baseFormat.getChannels(), baseFormat.getChannels()*2,
baseFormat.getSampleRate(),false);
}/*** init decoded audio stream*/protectedvoidinitDecodedAudioStream() {
decodedAudioStream=AudioSystem.getAudioInputStream(decodedFormat, audioStream);
}/*** get source data line
*
*@paraminput audio input stream
*@return*@throwsUnsupportedAudioFileException
*@throwsIOException
*@throwsLineUnavailableException*/protectedSourceDataLine getSourceDataLine()throwsUnsupportedAudioFileException, IOException,
LineUnavailableException {
DataLine.Info info=newDataLine.Info(SourceDataLine.class, decodedFormat);
SourceDataLine line=(SourceDataLine) AudioSystem.getLine(info);
line.open(decodedFormat);returnline;
}/*** play audio
*
*@throwsUnsupportedAudioFileException
*@throwsIOException
*@throwsLineUnavailableException*/protectedvoidplay()throwsUnsupportedAudioFileException, IOException, LineUnavailableException {
SourceDataLine line=getSourceDataLine();
line.start();intreadLenth=0;while(readLenth!=-1) {
readLenth=decodedAudioStream.read(AUDIO_BUFER,0, AUDIO_BUFER.length);if(readLenth!=-1) {
line.write(AUDIO_BUFER,0, readLenth);
}
}
line.drain();
line.stop();
line.close();
decodedAudioStream.close();
audioStream.close();
}
}