How to cut a video into smaller segment using ffmpeg in a Java program? The command works fine from terminal but doesn’t when I try the same in my program.
Here’s the code snippet
public static void main(String[] args) throws IOException { Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec("ffmpeg -i /Users/test/Desktop/demo.mp4 -ss 0 -t 2 -c:v copy copy.mp4"); }
Advertisement
Answer
Runtime.exec()
is fraught with difficulties. A particular problem with ffmpeg
is that it’s likely to produce output — to stdout
or stderr
or both — and take some time to complete. The output needs to be collected up and processed, even it it’s only copied to the terminal. Not only will the process block if it produces output and nothing consumes it, you really need to collect stderr
to see any errors.
Bear in mind that Runtime.exec()
is not a shell, and it won’t necessarily parse command lines the way a shell would. It won’t even necessarily look in the same places for executables as a shell will.
Another problem you’re likely to have is that your Java program might complete before the process spawned by exec()
does. You probably need a Process.waitFor()
after the exec()
if you want to wait.
I have some example code using Runtime.exec()
with stdout
/stderr
processing on GitHub. However, the perils in using Runtime.exec()
are discussed in many posts here.