java音頻播放示例分享(java若何播放音頻)。本站提示廣大學習愛好者:(java音頻播放示例分享(java若何播放音頻))文章只能為提供參考,不一定能成為您想要的結果。以下是java音頻播放示例分享(java若何播放音頻)正文
這是一份精簡後的代碼,可以或許支撐的格局非常無限。
package com.hongyuan.test;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class MusicTest {
public static final String MUSIC_FILE = "重逢一笑.wav";
public static void main(String[] args) throws LineUnavailableException,
UnsupportedAudioFileException, IOException {
// 獲得音頻輸出流
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(new File(MUSIC_FILE));
// 獲得音頻編碼對象
AudioFormat audioFormat = audioInputStream.getFormat();
// 設置數據輸出
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,
audioFormat, AudioSystem.NOT_SPECIFIED);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem
.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
/*
* 從輸出流中讀取數據發送到混音器
*/
int count;
byte tempBuffer[] = new byte[1024];
while ((count = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) {
if (count > 0) {
sourceDataLine.write(tempBuffer, 0, count);
}
}
// 清空數據緩沖,並封閉輸出
sourceDataLine.drain();
sourceDataLine.close();
}
}