獲取音頻文件時長
/**
* 獲取音頻播放時長,支持wav格式(環境無聲卡)
* @param filePath 文件授權地址
* @author knight-jzc
* @return 秒數
*/
public static Integer getDuration(String filePath){
try{
String bath = filePath.split(":")[0];
AudioInputStream ais;
String HTTP = "http";
String HTTPS = "https";
// 通過授權url獲取音頻輸入流
if (HTTP.equalsIgnoreCase(bath)||HTTPS.equalsIgnoreCase(bath)) {
ais = AudioSystem.getAudioInputStream(new URL(filePath));
} else {
ais = AudioSystem.getAudioInputStream(new File(filePath));
}
AudioFormat format = ais.getFormat();
// 新建文件獲取音頻輸出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (AudioSystem.isFileTypeSupported(AudioFileFormat.Type.WAVE,
ais)) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, outputStream);
}
// 獲取音頻比率和大小以及文件長度
long audioFileLength = outputStream.toByteArray().length;
int frameSize = format.getFrameSize();
int frameRate = (int) format.getFrameRate();
return (int) (audioFileLength / (frameSize * frameRate));
}catch (Exception e){
e.printStackTrace();
return 0;
}
}