开发者

How to run ffmpeg command in background from java

开发者 https://www.devze.com 2023-01-16 21:17 出处:网络
I am running a ffmpeg command from java Runtime.getRuntime().exec. ffmpeg command basically cut the images from live stream.

I am running a ffmpeg command from java Runtime.getRuntime().exec. ffmpeg command basically cut the images from live stream. Actually when i run thi开发者_运维问答s command without & then it works fine for five minutes after that it stops cutting images.

but when i use "&" in ffmpeg command it does not work at all.

there is no problem in live stream as when i ran this ffmpeg command from linux its working fine.

My main question is how to run a ffmpeg command in background from java.


The '&' is a shell directive to drop the task into the background. Running from Process.exec() doesn't involve the shell.

If your process is stalling (i.e. running but just not working) then I suspect that it's blocked waiting for you to consume stdout/stderr. You have to do this using threads to prevent the process blocking waiting for you to consume its output. See this SO answer for more details.

To run it in the background (i.e. whilst your Java process does other stuff) you need to:

  1. spawn a new thread
  2. invoke the process via Process.exec in this thread
  3. consume stdout/stderr (both in separate threads) and finally get the exit code


I know you ask for help for your command line problem in Java but you might be interest in an other solution.

Maybe you can give a try to this library: http://code.google.com/p/jjmpeg/

It's a wrapper for ffmpeg. Maybe you can try to create a java thread and run your command.


String livestream = "/Users/videos/video_10/video_1.mp4";

String folderpth = "/Users/videos/video_10/photos";

String cmd="/opt/local/bin/ffmpeg -i "+ livestream +" -r 10 "+folderpth+"/image%d.jpeg"; 

Process p = Runtime.getRuntime().exec(cmd);

The video was 10 sec. long and it created 100 jpeg's in photos folder. You have to provide the absolute path of the folder.

Also to find the path for ffmpeg binary use which ffmpeg in terminal. Mine was /opt/local/bin/ffmpeg.


You wrote it stops working after minutes. Did you check the exit code (Process.exitValue()). Also, did you check output stream and error stream from the external process?


Are you passing the arguments in an array? If it works for a while are you giving it all the expected arguments? (print it out and check). Here is an example of my ffmpeg that I dug out for you.

String[] ffmpeg = new String[] {"ffmpeg", "-ss", Integer.toString(seconds),"-i", in, "-f", "image2", "-vframes", "1", out};
Process p = Runtime.getRuntime().exec(ffmpeg);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号