Skip to content

Instantly share code, notes, and snippets.

@anta40
Created December 23, 2016 07:38
Show Gist options
  • Save anta40/ebd29561a434210d592c0f73d9995abf to your computer and use it in GitHub Desktop.
Save anta40/ebd29561a434210d592c0f73d9995abf to your computer and use it in GitHub Desktop.
a simple motion detection using webcam in Java
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
import com.leacox.process.FinalizedProcess;
import com.leacox.process.FinalizedProcessBuilder;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author anta40
*/
public class MotionDetector implements WebcamMotionListener {
private final int INTERVAL = 3000;
private String media_1, media_2 = "";
private boolean detected = false;
private boolean isPlaying = false;
private FinalizedProcess proc_idle, proc_video;
private FinalizedProcessBuilder pb1, pb2;
public MotionDetector() throws IOException{
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
media_1 = "idle.mp4"; // media played in loop when idle
media_2 = "advertisement.mp4" // media played when motion is detected
// we use VLC for playing videos
// assume that VLC is available in %PATH%
pb1 = new FinalizedProcessBuilder("vlc", media_1, "--fullscreen" ,"--repeat");
pb2 = new FinalizedProcessBuilder("vlc", media_2, "--fullscreen","vlc://quit");
// play the 'idle' video
proc_idle = pb1.start();
// check movement per INTERVAL
detector.setInterval(INTERVAL);
detector.addMotionListener(this);
detector.start();
}
@Override
public void motionDetected(WebcamMotionEvent wme) {
System.out.println(">>> movement "+counter);
++counter;
// Every time a motion is detected the video, kill the 'blank video' process, and start the 'advertisement video' process.
try {
proc_idle.close();
proc_idle.destroy();
} catch (IOException ex) {
// Logger.getLogger(MotionDetector.class.getName()).log(Level.SEVERE, null, ex);
}
try {
proc_video = pb2.start();
try {
// The duration of advertisement video is 64 seconds
// set the timeout
proc_video.waitFor(64000);
} catch (InterruptedException ex) {
// Logger.getLogger(MotionDetector.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
// assuming no motion is detected, kill the advertisement video, and play the blank video again
proc_video.close();
proc_video.destroy();
proc_idle = pb1.start();
}
} catch (IOException ex) {
//Logger.getLogger(MotionDetector.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws IOException {
new MotionDetector();
System.in.read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment