ffmpeg音视频转码
作者:互联网
使用ffmpeg对音视频格式转换
FFmpeg是领先的多媒体框架,能够解码,编码, 转码,mux,demux,流,过滤和播放人类和机器创建的几乎所有内容。
下载ffmpeg,官网地址:ffmpeg
下载完成后(Windows),需配置环境变量,将ffmpegPath的路径指定到你安装ffmpeg的具体路径,sourcePath的路径是需要转换的源文件路径,targetPath的路径是转换完成后存放的目标路径 。具体代码如下:
/**
* 音频转码
* @param ffmpegPath ffmpeg路径
* @param sourcePath 源文件路径
* @param targetPath 目标文件
*/
public static void audio(String ffmpegPath, String sourcePath, String targetPath){
List<String> convertDetailList = new ArrayList<String>();
convertDetailList.add(ffmpegPath);
convertDetailList.add("-i");
convertDetailList.add(sourcePath);
convertDetailList.add("-acodec");
convertDetailList.add("libmp3lame");
convertDetailList.add(targetPath);
executeConvert(convertDetailList);
}
/**
* 视频转码
* @param ffmpegPath ffmpeg路径
* @param sourcePath 源文件路径
* @param targetPath 目标文件
*/
public static void video(String ffmpegPath, String sourcePath, String targetPath){
List<String> convertDetailList = new ArrayList<String>();
convertDetailList.add(ffmpegPath);
convertDetailList.add("-i");
convertDetailList.add(sourcePath);
convertDetailList.add("-vcodec");
convertDetailList.add("libx264");
convertDetailList.add("-vb");
convertDetailList.add("384k");
convertDetailList.add("-r");
convertDetailList.add("18");
convertDetailList.add("-strict");
convertDetailList.add("-2");
convertDetailList.add("-ar");
convertDetailList.add("22050");
convertDetailList.add("-ab");
convertDetailList.add("64k");
convertDetailList.add("-coder");
convertDetailList.add("0");
convertDetailList.add(targetPath);
executeConvert(convertDetailList);
}
/**
* 视频截图(截取"00:05:55"时间的图片)
* @param ffmpegPath ffmpeg路径
* @param sourcePath 源文件路径
* @param targetPath 目标文件
*/
public static void videoScreenshot(String ffmpegPath, String sourcePath, String targetPath){
List<String> convertDetailList = new ArrayList<String>();
convertDetailList.add(ffmpegPath);
convertDetailList.add("-i");
convertDetailList.add(sourcePath);
convertDetailList.add("-y");
convertDetailList.add("-f");
convertDetailList.add("image2");
convertDetailList.add("-ss");
convertDetailList.add("00:05:55");
convertDetailList.add("-vframes");
convertDetailList.add("2");
convertDetailList.add(targetPath);
executeConvert(convertDetailList);
}
@SneakyThrows
private static void executeConvert(List<String> convertDetailList){
String line = null;
Process process = Runtime.getRuntime().exec(convertDetailList.toArray(new String[convertDetailList.size()]));
@Cleanup InputStream stream = process.getErrorStream();
@Cleanup InputStreamReader reader = new InputStreamReader(stream);
@Cleanup BufferedReader bufferedReader = new BufferedReader(reader);
StringBuffer stringBuffer = new StringBuffer();
while((line = bufferedReader.readLine())!=null){
stringBuffer.append(line).append("\n");
}
log.info("打印日志 {}", stringBuffer);
}
不足之处请赐教
标签:String,转码,sourcePath,targetPath,音视频,add,ffmpeg,ffmpegPath,convertDetailList 来源: https://blog.csdn.net/m0_46397664/article/details/105868910