FFmpeg命令在程序中无法将视频成功裁剪为较小的片段。

huangapple go评论77阅读模式
英文:

FFmpeg command to cut video into smaller segments not working programmatically

问题

如何在Java程序中使用ffmpeg将视频剪切成较小的片段?该命令在终端中运行正常,但在程序中尝试相同的命令时却无法运行。

以下是代码片段:

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");
}
英文:

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");
}

答案1

得分: 0

Runtime.exec()存在许多困难。ffmpeg的一个特殊问题是,它很可能会产生输出,输出可能是到stdoutstderr或者两者都有,并且完成所需的时间可能会较长。需要收集和处理输出,即使只是将其复制到终端上也是如此。如果它产生输出而没有任何消费,进程不仅会阻塞,而且您真的需要收集stderr以查看任何错误。

请注意,Runtime.exec()不是一个Shell,它不会像Shell一样解析命令行。它甚至不一定会在与Shell相同的位置寻找可执行文件。

您可能会遇到的另一个问题是,您的Java程序可能会在由exec()生成的进程之前完成。如果想要等待,可能需要在exec()之后使用Process.waitFor()

我在GitHub上有一些使用带有stdout/stderr处理的Runtime.exec()的示例代码。然而,在这里的许多帖子中都讨论了使用Runtime.exec()的风险。

[1] https://github.com/kevinboone/runtimeexec

英文:

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.

[1] https://github.com/kevinboone/runtimeexec

huangapple
  • 本文由 发表于 2020年9月15日 02:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63889789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定