4

I am running ffmpeg.exe through a Java code to encode a video file. How will my program come to know when ffmpeg terminated (i.e. video file is encoded)?

Here is the code:

Runtime.getRuntime().exec("ffmpeg -ac 2 -i audio.wav -i video.flv -sameq out.flv");
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
devashish jasani
  • 413
  • 1
  • 4
  • 15
  • 1
    You will discover that is a very fragile way to construct a `Process` when it encounters a path or file name containing a space. As general tips. 1) Use the methods that accept an array of arguments. 2) Use a `ProcessBuilder` for 1.5+ code, which then makes it slightly simpler to 3) Implement all the suggestions of [When Runtime.exec() won't](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html) BTW - why use ffmpeg rather than jffmpeg? – Andrew Thompson Jun 23 '12 at 21:27
  • 1
    What does this have to do with Xuggle? To my knowledge, ffmpeg & Xuggle are entirely separate projects. – Andrew Thompson Jun 23 '12 at 21:30
  • I was unaware about jffmpeg.Thank you. – devashish jasani Jun 23 '12 at 22:38

2 Answers2

5

You can use waitFor() method of java.lang.Process:

Process p = Runtime.getRuntime().exec("ffmpeg...");
int exitValue = p.waitFor()

With this, the current thread waits until the Process p has terminated.

EDIT:

You can try to see the output from ffmpeg:

class StreamDump implements Runnable {

    private InputStream stream;

    StreamDump(InputStream input) {
        this.stream = input;
    }

    public void run() {
        try {
            int c;
            while ((c = stream.read()) != -1) {
                System.out.write(c);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

and

Process p = Runtime.getRuntime().exec("ffmpeg.exe...");
new Thread(new StreamDump(p.getErrorStream()), "error stream").start();
new Thread(new StreamDump(p.getInputStream()), "output stream").start();
try {
    p.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("Exit value: " + p.exitValue());
jalopaba
  • 8,039
  • 2
  • 44
  • 57
0

I found a work around,if the file out.flv is tried to rename while it is being encoded it wouldn't allow,It can only be renamed after the encoding is over :

Runtime.getRuntime().exec("ffmpeg -ac 2 -i audio.wav -i video.flv -sameq out.flv");

File tempFile=new File("out.flv");
File renamedFile=new File("renamed.flv");
while(!tempFile.renameTo(renamedFile)); //try re-naming the file which is being encoded by ffmpeg

System.out.println("Encoding done");
devashish jasani
  • 413
  • 1
  • 4
  • 15