public static int doWaitFor(Process process) {
InputStream in = null;
InputStream err = null;
int exitValue = -1; // returned to caller when p is finished
try {
in = process.getInputStream();
err = process.getErrorStream();
boolean finished = false; // Set to true when p is finished
while (!finished) {
try {
while (in.available() > 0) {
// Print the output of our system call
Character c = new Character((char) in.read());
System.out.print(c);
while (err.available() > 0) {
// Print the output of our system call
Character c = new Character((char) err.read());
System.out.print(c);
// Ask the process for its exitValue. If the process
// is not finished, an IllegalThreadStateException
// is thrown. If it is finished, we fall through and
// the variable finished is set to true.
exitValue = process.exitValue();
finished = true;
} catch (IllegalThreadStateException e) {
// Process is not finished yet;
// Sleep a little to save on CPU cycles
Thread.currentThread().sleep(500);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
} catch (IOException e) {
e.printStackTrace();
if (err != null) {
try {
err.close();
} catch (IOException e) {
e.printStackTrace();
return exitValue;
Java调用外部命令使用 Runtime.getRuntime().exec(command) 。
在使用调用ffmpeg命令时,必须要读取执行命令输出流中的内容,程序才不会阻塞。否则缓冲读满后,进程会卡住。
视频转换会非常耗时,取决于硬件性能。在实际应用中,我们也可以开启线程去处理。
FFmpeg还提供C调用,公共库集成。以上方法并不是最优解决方案,仅提供一种参考。