I try running ffmpeg from Java, and for a couple of moments everything is working fine. I want ffmpeg to record my screen, and split the recording into small clips. The command is working fine from the terminal, but when I run it from Java I get at most 3 clips. Ffmpeg doesn’t write anything to the InputStream, so I have no idea what’s going wrong.
public static void execute(int frameRate, int width, int height, String windowTitle) {
String[] args = new String[]{
"ffmpeg",
"-hide_banner",
"-f", "gdigrab",
"-thread_queue_size", "1024",
"-rtbufsize", "256M",
"-framerate", "60",
"-offset_x", "0",
"-offset_y", "0",
"-video_size", "854x480",
"-draw_mouse", "1",
"-i", "title=Window Title* -something Like this",
"-c:v", "libx264",
"-r", "60",
"-preset", "ultrafast",
"-tune", "zerolatency",
"-crf", "28",
"-pix_fmt", "yuv420p",
"-movflags", "+faststart",
"-y",
"-f", "segment",
"-reset_timestamps", "1",
"-segment_time", "1",
"output%06d.mp4"
};
try {
Process p = Runtime.getRuntime().exec(args);
Thread thread = new Thread(() -> {
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("TEST");
try {
while ((line = input.readLine()) != null)
System.out.println(line);
System.out.println("Stopping with reading");
input.close();
} catch (IOException e) {
e.printStackTrace();
}
});
int exitCode = p.waitFor();
thread.start();
thread.join();
if (exitCode != 0) {
throw new RuntimeException("FFmpeg exited with code " + exitCode);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
I’ve run the same command in the terminal. That worked fine. I ran the code above, but that resulted in ffmpeg stopping after 3 clips. It kept showing as working from the task manager. As said before, ffmpeg doesn’t write anything to the InputStream, even though it normally does write a lot in the terminal. The weird thing is, when I stop my Java program, but accidentally keep ffmpeg running, it suddenly does everything I wanted it to.
WinnieTheDampoeh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.