Search code examples
javavideoencodingffmpegxuggle

When does ffmpeg terminate?


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

Solution

  • 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());