先導入:
java.io.*;
javax.sound.sampled.*;
public static void main(String[] args){
play();
}
public static void play() {
String fileUrl = "你的檔案路徑";
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileUrl));
AudioFormat aif = ais.getFormat();
SourceDataLine sdl = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,aif);
sdl = (SourceDataLine)AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
int nByte = 0;
byte[] buffer = new byte[128];
while(nByte != -1){
nByte = ais.read(buffer,0,128);
if(nByte >= 0)
sdl.write(buffer, 0, nByte);
}
sdl.stop();
}catch(UnsupportedAudioFileException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}