Java run linux(raspbian) command(omxplayer) and get output

1.7k views Asked by At

I create a program as below to execute a linux (raspbian) command: "omxplayer". But I don't know why I cannot get output from omxplayer as the time I type it into command line and hit Enter.But the output only show at the end of the video. So I want to get the output immediately after I type "omxplayer [video_name]" and hit "Enter" in my program. Just like the command line (terminal) work when I type directly into it in linux. This is my code:

public class testprog {
    public static void main(String args[]) throws IOException {

        String in = "";
        while(in!="exit")
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            in = reader.readLine();
            runCommand(in);
        }
    }

    public static void runCommand(String command)
    {
           String s;
         Process p;
         try {
             System.out.println("run command " + command);
             p = Runtime.getRuntime().exec(new String[]{"bash", "-c",command});

             MyInputStreamReader reader1 = new MyInputStreamReader(p.getInputStream());
             reader1.setTag("in");
             reader1.start();

             MyInputStreamReader reader2 = new MyInputStreamReader(p.getErrorStream());
             reader2.setTag("in");
             reader2.start();


             p.waitFor();
             System.out.println ("exit: " + p.exitValue());
             p.destroy();
         } catch (Exception e) {}

    }
}

class MyInputStreamReader extends Thread{
    boolean isStop = false;
    ReadEventHandler handler;
    String tag;
    InputStream in;
    public MyInputStreamReader(InputStream in)
    {
        this.in = in;
    }

    public void setHandler(ReadEventHandler handler) {
        this.handler = handler;
    }
    public void setTag(String tag)
    {
        this.tag = tag;
    }

    public void run()
    {
        byte[] buff = new byte[8192];
        while (true) {
            //String line;
            try {
                int len  = in.read(buff);
                if (len == -1)
                {
                    return;
                }

                String line = new String(buff, 0, len);
                if (handler!=null)
                    handler.onReceived(line);
                System.out.println(tag +" " + line);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
    public void dispose()
    {
        this.isStop = true;
    }
    public interface ReadEventHandler
    {
        void onReceived(String line);
    }
}

Any response is highly appreciated. Thanks

1

There are 1 answers

1
Brethlosze On

Did you checked this?

http://javedmandary.blogspot.com/2014/01/firing-up-raspberry-pi-omxplayer-using.html

I guess there is the code you're looking for.