/**
* 此方法需要用到第三方jar包 我這用到tritonus_share-0.3.6.jar
**/
private static final int EXTERNAL_BUFFER_SIZE = 128000;
public static void main(String[] args){
play("D:\\Backup\\ALARM8.WAV"); //可以放到while裏面循環播放音樂
}
/**
* 播放音頻文件 支持音頻格式 wav mid aif,此方法不支持mp3 wma au
*@param strFileName 文件路徑
*/
public static void play(String strFilename){
if (strFilename.length() <= 0)
{
printUsageAndExit();
}
//把聲音文件 放到文件對象裏
File soundFile = new File(strFilename);
//讀出這個聲音文件
AudioInputStream audioInputStream = null;
try
{
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
}
catch (Exception e)
{ //如果讀取文件失敗,則拋出這個異常
e.printStackTrace();
throw new MonitorException(e.getMessage());
}
//從這個audioInputStream流數據得到java能解讀的聲音格式
AudioFormat audioFormat = audioInputStream.getFormat();
//通過audioFormat格式得到正常播放的數據line
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try
{
line = (SourceDataLine) AudioSystem.getLine(info);
//得到了數據line後,line還沒準備好接受音頻數據, 這裏調用open 接收音頻數據
line.open(audioFormat);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
//line現在已經能接受數據了,但是還不能通過音頻設備播出, 這裏調用start 激活音頻設備
line.start();
//這裏把音頻流讀到緩存中,然後寫到line中播放
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1)
{
try
{
nBytesRead = audioInputStream.read(abData, 0, abData.length);
}
catch (IOException e)
{
e.printStackTrace();
}
if (nBytesRead >= 0)
{
int nBytesWritten = line.write(abData, 0, nBytesRead);
}
}
//等待所有的數據都播放完
line.drain();
//關閉line
line.close();
}
private static void printUsageAndExit()
{
System.exit(1);
}