由于项目需要,需要分割wav文件,看了网上的使用“jave”分割,测试后,发现分割后的wav文件无法播放,后续测试使用中间程序:ffmpeg
下载ffmpeg,配置好系统环境变量后
确保可以使用该命令。
Java代码
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @program
* @description
* @create 2023/2/8 14:31
**/
public class FfmpegWav {
/**
* 音频切割
*
* @param path 路径
* @param fileName 文件名
* @param timeLong 切割时长
* @return 返回切割后文件列表
*/
public static List<String> wavToCutting(String path, String fileName, int timeLong) {
Runtime run = null;
List<String> result = new ArrayList<>();
try {
long start = System.currentTimeMillis();
// 获取录音时长
File file = new File(path + fileName);
if (!file.exists()) {
return null;
}
int audioLength = (int) getTimeLen(file);
System.out.println("录音时长:" + audioLength);
int startTime = 0;
int endTime = 0;
run = Runtime.getRuntime();
while (endTime < audioLength) {
endTime += timeLong;
if (endTime > audioLength) {
endTime = audioLength;
}
String cutFile = (path + fileName.replace(".wav", "") + "_cut_" + startTime + "_" + endTime + ".wav");
String runCmd = "ffmpeg -i " + (path + fileName) + " -ss " + secondToTime(startTime) + " -to " + secondToTime(endTime)
+ " -y " + cutFile;
Process p = run.exec(runCmd);
System.out.println("执行:" + runCmd);
result.add(cutFile);
startTime = endTime;
}
long end = System.currentTimeMillis();
System.out.println(" 分割耗时:" + (end - start)/1000 + "秒");
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
// run调用lame解码器最后释放内存
assert run != null;
run.freeMemory();
}
return result;
}
/**
* 获取音频文件总时长
*
* @param file 文件
* @return
*/
public static long getTimeLen(File file) {
long result = 0;
if (file != null && file.exists()) {
Encoder encoder = new Encoder();
try {
MultimediaInfo m = encoder.getInfo(file);
long ls = m.getDuration();
result = ls / 1000;
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* 整数秒转换,精确到秒
*
* @param seconds
* @return
*/
private static String secondToTime(int seconds) {
if (seconds < 0) {
throw new IllegalArgumentException("Seconds must be a positive number!");
} else {
int hour = seconds / 3600;
int other = seconds % 3600;
int minute = other / 60;
int second = other % 60;
StringBuilder sb = new StringBuilder();
if (hour < 10) {
sb.append("0");
}
sb.append(hour);
sb.append(":");
if (minute < 10) {
sb.append("0");
}
sb.append(minute);
sb.append(":");
if (second < 10) {
sb.append("0");
}
sb.append(second);
return sb.toString();
}
}
public static void main(String[] args) {
System.out.println(wavToCutting("D:/softdata/projectRunData/wav/", "test.wav", 59));
}
}
maven依赖
<!-- https://mvnrepository.com/artifact/com.github.dadiyang/jave -->
<dependency>
<groupId>com.github.dadiyang</groupId>
<artifactId>jave</artifactId>
<version>1.0.5</version>
</dependency>
切割结果