import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class JavaCallFFmpeg extends Thread { private String theFmpgCmdLine = ""; public String getTheFmpgCmdLine() { return theFmpgCmdLine; } public void setTheFmpgCmdLine(String theFmpgCmdLine) { this.theFmpgCmdLine = theFmpgCmdLine; } /// 线程的run方法:线程的入口函数 public void run() { // 在run方法中编写需要执行的操作 openFFmpegExe(); System.out.println("fmpg thread over"); } //调用其他的可执行文件,例如:自己制作的exe,或是 下载 安装的软件. //转码命令: //推流命令: private void openFFmpegExe() { if(theFmpgCmdLine == null || theFmpgCmdLine.equals("")){ return; } /// 开启一个进程 Runtime rn = Runtime.getRuntime(); Process p = null; try { // 这里传递:ffmpeg推流命令行 p = rn.exec( theFmpgCmdLine ); /// 注意:ffmpeg输出的都是 "错误流": stdin, stdout, stderr, /// 注意:因为java可以直接读取"错误流",所以不用重定向 BufferedInputStream in = new BufferedInputStream(p.getErrorStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; System.out.println("Begin......"); while((lineStr = inBr.readLine()) != null){ //获得命令执行后在控制台的输出信息 //System.err.println("获得命令执行后在控制台的输出信息"); System.out.println(lineStr);// 打印输出信息 } inBr.close(); in.close(); } catch (Exception e) { System.out.println("Error exec:" + e.getMessage()); } } //1. 开启独立的线程 //2. 再开启一个进程,调用ffmpeg,转码、推流、... public static void main(String args[]) throws Exception { System.out.println("---main.start---"); JavaCallFFmpeg objFmpgThrd = new JavaCallFFmpeg(); //转码:ffmpeg -ss 0 -t 3 -i D:\\_movies\\__test\\ande_10.mp4 -vcodec libx264 -s 640x360 -y D:\\_movies\\__test\\ande_10-out1.mp4 /// 注意:因为java可以直接读取"错误流",所以不用重定向 String strFmpgCmdLine = "ffmpeg -ss 0 -t 3 -i -vcodec libx264 -s 640x360 -y ";///2>&1 objFmpgThrd.setTheFmpgCmdLine(strFmpgCmdLine); objFmpgThrd.start(); /// 等待线程结束 objFmpgThrd.join(); System.out.println("---main.bye---"); } }