获取wav格式音频时长。
Maven依赖
<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;
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为采样率。
说明
该工具类只能处理单声道音频,双声道会报错,多声道属于立体声范畴,提醒一下。
到此这篇关于Java轻松使用工具类实现获取wav时间长度的文章就介绍到这了,更多相关Java 获取wav时长内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!