Saturday, January 04, 2014

Firing up Raspberry PI omxplayer using Java code

The Pi has an excellent HDMI media player called omxplayer but it fails short in terms of interface to interact with , for starters by default you can interact with it only via command line for example the following command will play an mp4 file:

omxplayer -r -o hdmi myVideoFile.mp4

I have been working on a Spring Boot Restful application to be able to control the OMXPlayer on the Raspberry Pi . For now my Spring Boot application which runs on Raspberry Pi itself only provides a means to play a specified file and to stop the omxplayer .

Now whats interesting is that Spring Boot provides an easy means to quickly put up an executable jar file which can expose Restful endpoints . So next step is how to call the command above from Java on the Pi which is basically a unix system .


Strangely as it sounds it took me a while to figure this out whilst navigating through stackoverflow , well its not that complicated.

All you need is a ProcessBuilder :

ProcessBuilder pb = new ProcessBuilder("bash", "-c", "omxplayer -r -o hdmi myVideoFile.mp4");
Process process = pb.start();

StringBuffer sb = new StringBuffer();

BufferedReader reader = new BufferedReader(new InputStreamReader(

String line = reader.readLine();
while (line != null) {
line = reader.readLine();

The ProcessBuilder will execute a Java process which in turn execute your omxplayer play command on the unix system , the output of this operation is returned back to the sb StringBuffer . 


Currently I couldn't find an elegant way to stop the playback though so what am doing is that am literally killing the process using the kill command e.g :

kill -9 3144

where 3144 is some PID (Process ID) which you need to capture to kill the process (executed through the process builder) , note that each time you fire off the omxplayer it will have a different ID.

Note that I use the following  command to get the PID 

ps -ef |egrep \"/usr/bin/omxplayer.bin

This will give you something as shown in the screenshot below :

Note that in either case you can use the same codes above to execute the :

1. codes that will return you the output from which you can then extract the PID 
2. execute the kill command to stop the process 

So that's as simple as it is for now.

No comments: