电脑需安装 ffmpeg 下载地址
FFmpeg
核心代码如下,文末包含示例项目
package com.ruoyi.common.utils.mp3;
import com.ruoyi.framework.config.RuoYiConfig;
public class Mp3Utils {
/**
* ffmpeg执行路径
*/
private static String ffmpegExePath = "E:\\soft\\development\\windows\\ffmpeg-5.1.2-full_build\\ffmpeg-5.1.2-full_build\\bin\\ffmpeg.exe";
public static void main(String[] args) {
String start = "00:00:08.551";
String end = "00:01:04.023";
String input = "D:\\FFOutput\\2023-01-11\\2023-01-11.aac";
String out = "D:\\FFOutput\\2023-01-11\\out.aac";
mp3Cut(start, end, input, out);
// String video = "C:\\Users\\Lenovo\\Downloads\\Video\\2023-01-11.ts";
// videoToMp3(video);
}
/**
* 切割mp3 文件
* @param start
* @param end
* @param input
* @param out
*/
public static void mp3Cut(String start, String end, String input, String out) {
//E:\ffmpeg\bin\ffmpeg.exe -i E:/tlb/365.mp3 -ss 00:00:08.551 -to 00:01:04.023 -y E:/tlb/365/5.mp3
String cmd = ffmpegExePath + " -i " + input + " -ss " + start + " -to " + end + " -y " + out;
try {
Runtime runtime = Runtime.getRuntime();
Process exec = runtime.exec(cmd);
exec.waitFor();
exec.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将秒表示时长转为00:01:02.500格式,精确到毫秒
*
* @param time 秒数时长
* @return 字符串格式时长
*/
public static String parseTimeToString(String time) {
String[] times = time.split("\\.");
Integer second = Integer.valueOf(times[0]);
String nx = "000";
if (times.length > 1) {
nx = times[1];
int length = nx.length();
if (length < 3) {
nx += "0";
} else if (length > 3) {
nx = nx.substring(0, 3);
}
}
return secondToTime(second) + "." + nx;
}
//整数秒转换,精确到秒
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();
}
}
/**
* 切割mp3 文件
* @param video
*/
public static void videoToMp3(String video) {
int i = video.lastIndexOf(".");
String out = video.substring(0,i);
out = out+ ".mp3";
System.out.println(out);
String cmd = ffmpegExePath + " -i "+video+" -threads 10 -preset ultrafast -f mp3 "+out+" ";
try {
Runtime runtime = Runtime.getRuntime();
Process exec = runtime.exec(cmd);
exec.waitFor();
exec.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getAbsPath(String path){
path = RuoYiConfig.getProfile() + path.replace("/profile","");
return path;
}
}
示例项目仓库地址:
https://gitee.com/weifuqiang/ffmpeg-test/tree/master
版权声明:本文为qq_29384639原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。