借助第三方工具ffmpeg合成视频
需求:在小破站上下载了一些视频,但是放到电脑里面看,我擦,声音文件和视频文件是分开的。
- 正确安装ffmpeg并配置好环境变量。
- Java代码测试
转载指明源头
里面是下载的视频和音频
我就上代码递归了,只要用正确的ffmpeg的命令和Java调用ffmpeg.exe的程序,就可以合成啦。
package com.lovely.test;import java.io.BufferedReader;
import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;/*** * 视频中获取音频文件* */public class TestFfmpeg {// FFmpeg全路径private static final String FFMPEG_PATH = "D:\\softWare\\tools\\joyTool\\ffmpeg\\bin\\ffmpeg.exe";public static void main(String[] args) {String path = "E:\\StudyVedio\\ComputerScience\\US";try {getAll(path);} catch (Exception e) {e.printStackTrace();}}/*** 具体合成视频函数* @param videoInputPath* 原视频的全路径* * @param audioInputPath* 音频的全路径* * @param videoOutPath* 视频与音频结合之后的视频的路径*/public static void convetor(String videoInputPath, String audioInputPath, String videoOutPath)throws Exception {Process process = null;InputStream errorStream = null;InputStreamReader inputStreamReader = null;BufferedReader br = null;try {// ffmpeg命令String command = FFMPEG_PATH + " -i " + videoInputPath + " -i " + audioInputPath+ " -c:v copy -c:a aac -strict experimental " +" -map 0:v:0 -map 1:a:0 "+ " -y " + videoOutPath;process = Runtime.getRuntime().exec(command);errorStream = process.getErrorStream();inputStreamReader = new InputStreamReader(errorStream);br = new BufferedReader(inputStreamReader);// 用来收集错误信息的String str = "";while ((str = br.readLine()) != null) {System.out.println(str);}process.waitFor();} catch (IOException e) {e.printStackTrace();} finally {if (br != null) {br.close();}if (inputStreamReader != null) {inputStreamReader.close();}if (errorStream != null) {errorStream.close();}}}// 递归函数public static void getAll(String path) throws Exception {String videoInputPath = "";String audioInputPath = "";String videoOutPath = "";File file = new File(path); if (file.isDirectory()) {File[] files = file.listFiles();for (File f : files) {getAll(f.getPath());if (f.isFile()) { if (f.getName().endsWith(".m4s")) {if (f.getName().endsWith("audio.m4s")) audioInputPath = file.getPath() + "\\audio.m4s";if (f.getName().endsWith("video.m4s"))videoInputPath = file.getPath() + "\\video.m4s";videoOutPath = file.getPath() + "\\all.mp4";if (!videoInputPath.equals(""))convetor(videoInputPath, audioInputPath, videoOutPath);}}}}}
}
我最后用了好几分钟合成了30个完整的视频。体会了递归的强大。