Saturday, May 7, 2011

How to build your own video recorder using Flex and AIR

Needed Resources:

Final Product:
A simple AIR application that records a video stream from a webcam and saves a temporary FLV file to the desktop. The UI will consist of a window displaying the current video feed and a button to start and stop recording.
Execution:
  1. Create a WebcamPanel class that extends off of the Panel class and will display the video feed:
    This class will basically consist of a method "insertWebcamVideo" that will build the UIComponent and attach a Video object to it.

    public function insertWebcamVideo():void{
    var videoHolder:UIComponent = new UIComponent();
    var camera:Camera = Camera.getCamera();
    video = new Video(camera.width*2, camera.height*2);
    video.attachCamera(camera);
    videoHolder.addChild(video);
    addChild(videoHolder);
    videoHolder.y =10;
    }
  2. Attach the WebcamPanel our main mxml file:
    <webcam:WebcamPanel id="webCam_pnl" width="360" height="320" />
  3. Create a button to toggle record off and on:
    <mx:Button id="record_btn" label="Record" click="recordPushed()" />
  4. Setup the recordPushed method to initialize our FLV file via the SimpleFLVWriter class if the label is "Record." In addtion to writing the header information for the file, this code sets up the interval that will take snapshots of the webcam feed:

    if(record_btn.label == "Record"){
    curVidFile = File.createTempFile();
    myWriter.createFile(curVidFile, 360,320, 10);
    recordInterval = setInterval(recordVid, 100);
    record_btn.label = "Stop";
    }
  5. For the else clause of our "if" statement we will close up the FLV file and copy it to the desktop:

    }else{

    clearInterval(recordInterval);
    myWriter.closeFile();
    var newFileNameStr:String = curVidFile.name.split(".tmp").join(".flv");
    var desFile:File = new File(File.desktopDirectory.nativePath +"\\" +newFileNameStr);
    curVidFile.copyTo(desFile);
    record_btn.label = "Record";
    }
  6. The code for the snap shot interval:

    private function recordVid():void{
    var snapshot:BitmapData = new BitmapData(320, 240, true);
    snapshot.draw(webCam_pnl.video);
    myWriter.saveFrame( snapshot );
    }
  7. Hook up a webcam and compile your project and viola!

No comments:

Post a Comment