在java程序中播放以.wav格式的音频文件

时间:2022-02-11 16:28:34
package com.lolo;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.DataLine;

public class PlayMusic {

// 程序退出时执行的代码
public void doShutDownWork() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
//Toolkit.getDefaultToolkit().beep();
Play();
Play();
} catch (Exception ex) {
}
}
});
}

//播放音频文件
public void Play(){
String fileurl = "file/tada.wav";
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();

//play
int nByte = 0;
byte[] buffer = new byte[128];
while(nByte != -1){
nByte = ais.read(buffer,0,128);
if(nByte >= 0){
int oByte = sdl.write(buffer, 0, nByte);
//System.out.println(oByte);
}
}
sdl.stop();
}catch(UnsupportedAudioFileException e){
e.printStackTrace();
} catch (IOException e) {
// TODO 自动产生 catch 区块
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO 自动产生 catch 区块
e.printStackTrace();
}
}
}


javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file异常是经常出现的,不要慌,查看自己的格式路径,只要格式路径对了,就不会报错。