时间:2021-12-09 18:07:13 | 栏目:JAVA代码 | 点击:次
获取wav格式音频时长。
<dependency>
<groupId>org</groupId>
<artifactId>jaudiotagger</artifactId>
<version>2.0.1</version>
</dependency>
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:\\csdn\\dzgz.wav");
}
}
输出结果:

duration为音频时长,单位毫秒,sampleRate为采样率。
该工具类只能处理单声道音频,双声道会报错,多声道属于立体声范畴,提醒一下。
