在java进程中运行ffmpeg命令在waitFor()中挂起

Mah*_*a M 5 java ffmpeg

我正在运行ffmpeg命令为给定的图像(img001.jpg、img002.jpg ...)生成视频,它正在创建幻灯片.mp4,但它无限等待:

public class Ffmpeg {

public static void main(String[] args) throws IOException, InterruptedException {
    String path = "E:\\pics\\Santhosh\\FadeOut\\testing";       
    String cmd = "ffmpeg -r 1/5 -i img%03d.jpg -c:v libx264 -r 30 -y -pix_fmt yuv420p slide.mp4";
    runScript (path, cmd);
}

private static boolean runScript(String path, String cmd) throws IOException, InterruptedException {       
    List<String> commands = new ArrayList<String>();
    commands.add("cmd");
    commands.add("/c");
    commands.add(cmd);
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File(path));
    pb.redirectErrorStream(true);
    Process process = pb.start();   
    flushInputStreamReader(process);                
    int exitCode = process.waitFor();
    return exitCode == 0;
}    
}

private static void flushInputStreamReader (Process process) throws IOException, InterruptedException {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line=null;
            StringBuilder s = new StringBuilder();
            while((line=input.readLine()) != null) {            
                s.append(line);
            }
        }
Run Code Online (Sandbox Code Playgroud)

有什么建议?

编写函数flushInputStreamReader后,其工作

小智 4

除了读取 ErrorStream 之外,还有更好的方法来处理此问题。

添加-loglevel quiet到命令中,以便 ErrorStream 不会溢出并首先阻塞进程。