import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class MyPlayer {
private String fileName=null;
public MyPlayer(String fileName){
this.fileName=fileName;
}
public void play() throws Exception{
File file=new File(fileName);
AudioInputStream stream=AudioSystem.getAudioInputStream(file);
AudioFormat format=stream.getFormat();
DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);
SourceDataLine line=(SourceDataLine)AudioSystem.getLine(info);
byte[] buf=new byte[512 * 1024];
line.open();
line.start();
int nbytes=0;
while(nbytes!=-1){
nbytes=stream.read(buf,0,buf.length);
if(nbytes>=0) line.write(buf, 0, nbytes);
}
line.drain();
line.close();
System.out.println("play over.");
}
public static void main(String[] args) throws Exception{
MyPlayer player=new MyPlayer("1.wav");
player.play();
}
}
说明:
1. 准备
SourceDataLine 播放使用的Line,通过AudioSystem.getLine(info)得到.
DataLine.Info 要用到AudioFormat
AudioFormat 可以new,本例用 AudioInputStream.getFormat()
2. 播放
SourceDataLine.open()
SourceDataLine.start()
SourceDataLine.write() 主要通过这个函数播放
3. 缓冲区
本例中定义512K
阅读(1366) | 评论(2) | 转发(0) |