本篇文章小编给大家分享一下Java轻松使用工具类实现获取wav时间长度代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
获取wav格式音频时长。
Maven依赖
org jaudiotagger 2.0.1
工具类
import org.jaudiotagger.audio.wav.util.WavInfoReader;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/** @Author huyi @Date 2021/9/30 14:46 @Description: 音频工具类 */
public class AudioWavUtils {
public static void getWavInfo(String filePath) throws Exception {
File file = new File(filePath);
WavInfoReader wavInfoReader = new WavInfoReader();
RandomAccessFile raf = new RandomAccessFile(file, "r");
// wav音频时长
long duration = (long) (wavInfoReader.read(raf).getPreciseLength() * 1000);
// wav音频采样率
int sampleRate = toInt(read(raf, 24, 4));
System.out.println("duration -> " + duration + ",sampleRate -> " + sampleRate);
raf.close();
}
public static int toInt(byte[] b) {
return ((b[3] << 24) + (b[2] << 16) + (b[1] << 8) + (b[0]));
}
public static byte[] read(RandomAccessFile rdf, int pos, int length) throws IOException {
rdf.seek(pos);
byte[] result = new byte[length];
for (int i = 0; i < length; i++) {
result[i] = rdf.readByte();
}
return result;
}
public static void main(String[] args) throws Exception {
getWavInfo("E:csdndzgz.wav");
}
}
输出结果:
duration为音频时长,单位毫秒,sampleRate为采样率。
说明
该工具类只能处理单声道音频,双声道会报错,多声道属于立体声范畴,提醒一下。