RSS

Actionscript 3 Webcam Configure

This entry was posted on Feb 24 2009

webcamconfig

Setting up a webcam in Flash has always been pretty simple. I feel there are two cases in flash that you would use the webcam in a project: Streaming video for video chat or using it as a tool to take a photo. These two cases have completely different purposes and thus you want your camera setup properly for each.

Setup Your Camera
First, let’s setup your camera and a video instance for playback. This code will setup a default camera and default video instance. Both will be setup for 320×240 playback.

1
2
3
4
var camera:Camera = Camera.getCamera();
var video:Video = new Video(); 
video.attachCamera(camera);
addChild(video);

 

Setup Camera for Streaming Video Chat
Setting up your camera for streaming video chat involves a little more work and planning than just using it to take a photo within the player. Streaming video will require you to sacrifice video quality for speed, especially if you need to sync the video with audio. There are two methods of the Camera class that we will use to balance video quality and frame rate with bandwidth: Camera.setQuality() and Camera.setMode(). setQuality() is used to specify bandwidth and overall image quality of the Camera’s output video. Adobe’s Help Documentation has this to say:

  • To indicate that bandwidth use takes precedence, pass a value for bandwidth and 0 for quality . Flash Player transmits video at the highest quality possible within the specified bandwidth. If necessary, Flash Player reduces picture quality to avoid exceeding the specified bandwidth. In general, as motion increases, quality decreases.
  • To indicate that quality takes precedence, pass 0 for bandwidth and a numeric value for quality . Flash Player uses as much bandwidth as required to maintain the specified quality. If necessary, Flash Player reduces the frame rate to maintain picture quality. In general, as motion increases, bandwidth use also increases.
  • To specify that both bandwidth and quality are equally important, pass numeric values for both parameters. Flash Player transmits video that achieves the specified quality and that doesn’t exceed the specified bandwidth. If necessary, Flash Player reduces the frame rate to maintain picture quality without exceeding the specified bandwidth.

Lets setup our code to have medium compressed quality and a frame rate of 15.

1
2
3
4
5
6
7
8
9
10
var bandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
var quality:int = 50; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
var camera:Camera = Camera.getCamera();
camera.setQuality(bandwidth, quality);
camera.setMode(320,240,15,true); // setMode(videoWidth, videoHeight, video fps, favor area)

// Now attach the webcam stream to a video object.
var video:Video = new Video();
video.attachCamera(camera);
addChild(video);

Depending on your project, you can change bandwidth, quality, and frame-rate settings to find the best combination. I would suggest setting the video capture size smaller, then stretching it up. This will allow for a higher frame rate since you are sending smaller video that is stretched. The video is a littler blurry, but if you plan on having lots of movement, having a higher frame-rate will be more important.

 

Setup Camera to take a photo
This type of configuration isn’t a whole lot different the the code example above. The main difference is that we aren’t passing constant amounts of data to a streaming server each second. Instead, we just need to get the camera’s data once. So, we can up the quality and frame rate to our hearts content (granted the user’s hardware allows for the settings).

Here is the above example, but with maxed out configuration for high photo quality.

 

1
2
3
4
5
6
7
8
var bandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
var quality:int = 100; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
var camera:Camera = Camera.getCamera();
camera.setQuality(bandwidth, quality);
camera.setMode(320,240,30,false); // setMode(videoWidth, videoHeight, video fps, favor area)
var video:Video = new Video();
video.attachCamera(camera);
addChild(video);

Feel free to comment with any questions. Check out my other post for more AS3 Camera quirks and tips.


64 Responses to “Actionscript 3 Webcam Configure”

  1. Great job…
    Very very helpfull examples
    Thaks


  2. Thanks Sudhir, glad I could help!


  3. Wow! I don’t know much about the vast actionscript libs, and was worried I wouldn’t be able to figure this out for a few weeks. THANK YOU VERY MUCH for providing such a simple example!

    Do you also have any short examples that explain how to connect the video stream to a Red5 and/or Flash Media Server? My company is leaning more towards Red5, since it’s open source, but I’m guessing any example would be about the same.

    :)


  4. Chad,
    I’m happy that I could help. Connecting to a Red5 server will be the same as connecting to a FMS (Flash Media Server). I have another quick tutorial about setting up an RTMP stream with Flash media server: http://blog.728media.com/2008/08/03/connecting-to-a-flash-media-server-using-rtmp/


  5. can I use these codes with a standard javascript in my html or do I need to use flash editor? does it have to be flash cs 3 or 4?

    this doesnt seem to work?

    SCRIPT LANGUAGE=JavaScript>

    LoadCamera()

    function LoadCamera() {

    alert(“ok”);

    var camera:Camera = Camera.getCamera();
    var video:Video = new Video();
    video.attachCamera(camera);
    addChild(video);

    var bandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
    var quality:int = 50; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
    var camera:Camera = Camera.getCamera();
    camera.setQuality(bandwidth, quality);
    camera.setMode(320,240,15,true); // setMode(videoWidth, videoHeight, video fps, favor area)
    var video:Video = new Video();
    video.attachCamera(camera);
    addChild(video);

    }


  6. Bruce,
    This is tutorial will only work in Flash using Actionscript.

    In order to view a webcam through javascript, you would need to have the webcam publishing to your server, then updating the IMG in your HTML. For refreshing the image, you could use this: http://www.ajaxcam.com/


  7. I have been working with the motion detection in as3 and I was wondering if you could shed some light… How do you set the video to a larger view, say 720, 540? Also how do you set the video representation to mirror the subject?

    Thanks!


  8. Hi

    Is there any way to have a preview of the image quality without seeing it from streaming server?

    I have a preview video attached to the camera but whatever quality or BW I set I can’t see the change, unless I connect that video to streaming server and see through live site how it looks.

    thanks
    Cris


  9. Cris,
    to force the preview to use the quality settings you need to add:

    camera.setLoopback( true );

    Regards,
    Ivaylo


  10. Great example to work from. If you’re using it to take a photo, how does Flash save/post the data to store it as a JPG? Any references would be greatly appreciated.


  11. cent,
    Once you capture the BitmapData of a display object (in this case the video that is playing back the webcamera), you have two choices to get a jpg file.

    1.) POST the BitmapData as a ByteArray to a webservice that opens a new window with the JPG.

    2.) You can use the Adobe JPG or PNG libraries to convert the BitmapData to the correct format and in Flash Player 10 save that BitmapData as an image to the user’s hard drive.

    http://code.google.com/p/as3corelib/


  12. I’m very interesting in the streaming for video chat part, but when I copied and pasted it I just got a white window when I tried to run it. It came up with the prompt asking for me to allow or deny the camera. I click allow and I get just the white window. Also how would someone else be able to see the live stream? I would take it they would have to go to a different page that would somehow play what your code is capturing. Any help would be appreciated. Thanks!


  13. Fedll,
    There are three possible reasons why your camera might not be showing in your Video object.

    1.) You don’t have a webcamera
    2.) You aren’t attaching the camera to the Video object
    3.) Your camera is already being used by another application or browser window.

    In order for users to watch the live stream, you would need to publish your camera to a NetStream that is connnected to a media server (like Flash Media Server) and pull that stream down on another page for live playback. So in the end you would have two applications: one to broadcast the video and another to receive and playback the stream.

    Setting up a FMS is quick and easy,
    http://blog.728media.com/2008/08/03/connecting-to-a-flash-media-server-using-rtmp/


  14. thank you sooo much. great help!


  15. very useful, much thanks!


  16. I need help
    how can webcam or camera auto detect which webcam are active possible
    understand?


  17. Mukler,
    The guys over at Squidder.com have a post that should help you out.
    http://www.squidder.com/2009/03/09/trick-auto-select-mac-isight-in-flash/


  18. thank you very much!!!!!!!!!!!!!!!
    but what about pc?
    my machine pc has not usb video else see you my pic device
    http://img36.imageshack.us/img36/2200/sssfm.jpg

    how? idea???


  19. Really great tutorial, straight forward and to the point. Good job!


  20. thanks for that, how then would you take the snapshot?


  21. Marc,
    If you want to take a “snapshot” of the video object, you will need to get your Video object’s bitmap data.

    Quasimondo has a tutorial that should help get you by:
    http://www.quasimondo.com/archives/000670.php


  22. Thanks a lot for a great tutorial. Couldn’t understand why my cam shot so bad pics… put after input from your tut… everything works smoothly. :-D


  23. Hi,

    I’m working with webcams in Flash at the moment and was wondering if anyone could tell me how to flip the image so that the movement doesn’t appear inverted.
    Hope someone can help me out and I look forward to hearing from anyone.

    Thanks.


  24. In order to flip the video you can adjust the scaleX property to -1. So your code would look like this:

    myVideo.scaleX *= -1;

    Hope this helps!


  25. I’ve been messing with the scripts trying to make it bigger. I keep failing. Is there anyway to make the video bigger with the 3rd example? And also, can you help with sound importing? And do you think you can help me create a video capture? I know this is probably too much to be asking, but I would like help for the larger screen the most.

    thanks

    Jeff


  26. Hey,

    Is there also an easy way to capture video? I can’t find it anywhere on the internet…

    Thanks!

    Susie


  27. You would need to use something like Flash Media Server or Red5(free) to capture and save video.


  28. Thanks Dear.


  29. Hi, Currenly i m working with my Graduation Project. And i am going to make something related to the motion detection with a webcam:
    I have prepared two animation. Animation 1 will be played in loop. When the audience touched on the screen, Animation 2 will be shown. .

    As i m very fresh to the Action Script. Would you please suggest any tutorial for me? Million Thanks!!

    Toby


  30. Hi, i’m in a current development of a webchat, and i was wondering, if there is any way, to improve the quality of the video ( i’m working with FluorineFx in the server side app ). I’ve heard, than, with Flash CS5, and ActionScript 3, it’s possible to encode, using MP4 codec. Is this true?

    Thanks anyway, this example was very helpful!!!


  31. Encoding the video is handled using whatever server side app being used. I know Flash Media Interactive Server 3.5 does allow for MP4/FV4 media encoding of a live stream. It is costly though:

    http://www.adobe.com/products/flashmediainteractive/


  32. Thanks for the tutorial.

    Is it possible to change the size of the image to, lets say, 1024×768?

    Does it deppends on the webcam resolution?

    I´m trying to change the size but it does not change.


  33. Felipe,
    The camera’s output is based off it’s capabilities. This limits what you can force the camera to deliver; an image larger than it’s max resolution or a frame rate higher than it’s ability. The way around making the video larger is to just scale up your Video object that you assigned to the camera’s playback. Since the Video class is an extension of a DispalyObject, you can alter it anyway you would a MovieClip or Sprite.

    Hope this helps.


  34. I try the same codes
    var camera : Camera;
    var video: Video;

    camera =Camera.getCamera();
    video = new Video();
    video.attachCamera(camera);

    But my webcam is not accessible and the output shows the screen capture.

    I am using Laptec webcam, is there is any issue with driver based webcam.

    please help me.


  35. Thank you, mate! Was looking for that


  36. Thank you for the short and good examples, better then the manual :-)


  37. Hi. I am a student and need some help with the implementation of a a webcam setting in Actionscript. I believe it is a pretty quick fix, however, I do not know how to fix the problem. I have some Actionscript I found online which performs face-tracking in flash. However, the video that it puts out is reversed and not mirrored correctly. I read a comment that said to flip the video by using this: myVideo.scaleX *= -1; However, I do not know where exactly to insert this into my Actionscript file. Could someone please show me exactly where to insert this line of code in my actionscript file, or if there’s some other code I need to use. I can provide the html link to download the actionscript file if needed…it is also listed as my website link on this comment. Any help would be appreciated!!! Thank you so much!


  38. You can add that code right after your Video object is created but before any face tracking code tries to access your Video object.


  39. For the mirror effect you have to set the scaleX and the Position X relatively to the width like that :

    video.x = video.width;
    video.scaleX *= -1;


  40. Tried your code w/ Flash Builder 4 for a AIR flex project. When I try to compile, I am getting the error:
    1061: Call to a possibly undefined method attachCamera through a reference with static type Video.

    When I use code completion, the method does not appear in the list. When I went back to Flex 3.5, I could find the method in the code completion, but it still would not compile. I have cut-and-paste your example as is, so I am wondering if you have any idea’s.


  41. Further to the above. The code does compile under 3.5, but I am getting a runtime error:

    Error #1034: Type Coercion failed: cannot convert flash.media::Video@374c089 to mx.core.IUIComponent.

    I am invoking your code thru a button click event. The error seems to be thrown on the addChild(video) line.


  42. Hello there,

    Congrats on the really easy to follow tutorial.

    I have on major problem though…my Flash Player won’t display the webcamera output. It only shows either a black screen, either a green pixeled one.

    The webcam works with all other programs on my Windows 7 machine.

    Flash player is 10.1

    Perhaps you could help ? Thank you !


  43. I’m trying to take a 800×600 screen shot as bitmap data and no matter how large i make the video, or the bitmap grabber, I always wind up with a video capture of 320 x 240

    var bandwidth:int = 0;
    var quality:int = 100;
    var camera:Camera = Camera.getCamera();
    camera.setQuality(bandwidth, quality);
    camera.setMode(800,600,120,true);
    var loader:Video = new Video();
    loader.attachCamera(camera);
    loader.width = 800;
    loader.height = 600;
    addChild(loader);

    stage.addEventListener(MouseEvent.CLICK,snapShot);
    function snapShot(e:MouseEvent):void
    {
    var loaderBMD:BitmapData = new BitmapData(800,600);
    loaderBMD.draw(loader);
    var bm:Bitmap = new Bitmap(loaderBMD);
    bm.smoothing = true;
    rec = new Sprite;
    rec.addChild(bm);
    addChild(rec);
    }

    I’ll get a 320×240 image, with the rest of the space filled with an empty “rec” movie clip


  44. Try putting your Video object in an empty sprite then get the BitmapData of that sprite.


  45. how can i monitor the bandwidth usage in flex 3.5


  46. how can i find bandwidth usage in flex?


  47. How can I adjust EXPOSURE of webcam and brightness and contrast ????


  48. Camera object don’t have that property . Actionscript 2 or 3.


  49. Here’s a working solution for taking larger than 320×240 photos.

    //define class accessible variables
    private var bm:Bitmap;
    private var bandwidth:int = 0;
    private var quality:int = 100;
    private var camera:Camera = Camera.getCamera();
    private var vidloader:Video = new Video();
    private var rec:Sprite = new Sprite;

    //method to set up camera

    private function onGetCamera(e:MouseEvent):void{
    //check for camera
    //if (camera.getCamera() != null) {
    vidloader.width = 640;
    vidloader.height = 480;

    camera.setQuality(bandwidth, quality);
    camera.setMode(640,480,10,true); // setMode(videoWidth, videoHeight, video fps, favor area)

    //this matrix doubles the size and flips the preview so it’s easier to position yourself
    var ma:Matrix = new Matrix();
    ma.a = -2;
    ma.d = 2;
    ma.tx = vidloader.width;

    this.vidloader.transform.matrix = ma;

    //attach camera to the video
    vidloader.attachCamera(camera);

    // add the video to a sprite which when rendered as bitmapdata in the next function, draws a higher def image
    rec.addChild(vidloader);

    //add video preview to the stage
    addChild(rec);

    }

    public function actuallyCaptureTheShot():void{

    var loaderBMD:BitmapData = new BitmapData(640,480);
    loaderBMD.draw(rec);

    var originalBitmapData:BitmapData = loaderBMD;
    var scaleFactor:Number=2;
    var newWidth:Number=originalBitmapData.width*scaleFactor;
    var newHeight:Number=originalBitmapData.height*scaleFactor;

    var scaledBitmapData:BitmapData = new BitmapData(newWidth,newHeight,true,0×00000000);

    scaledBitmapData.draw(originalBitmapData);

    bm = new Bitmap(scaledBitmapData, “auto”, true);

    //add the snapshot to the stage, or add it to an existing movieclip so you can move it around maybe!
    addChild(bm);

    }


  50. can u give a much detail of how i can stream video from webcam to be viewed by people


  51. Great information in the tutorial and in the comments. I am trying to find out if it is possible to record a video inside Flash (not streaming to a server and not saving to hard drive). If so, what format is the video in.. if the snapshot is bitmap I am guessing something not compressed. If there are any code example of recording and playing back video out there that would help me a great deal.

    Thanks!


  52. Thank you so much.. It was very helpful for us


  53. hi,
    i am still new in flash as3..hope can get help from you :)
    my problem is the webcam image is very small, how am i going to make it bigger(for example: 430*500)?
    i had change *camera.setMode(430,500,15,true);* , but it does not change the size of the webcam image.

    below are the script:

    var bandwidth:int = 0;
    var quality:int = 100;
    var camera:Camera = Camera.getCamera();
    camera.setQuality(bandwidth, quality);
    camera.setMode(320,240,15,true);
    var video:Video = new Video();
    video.attachCamera(camera);
    addChild(video)

    var imgBD:BitmapData;
    var imgBitmap:Bitmap;

    shotBtn.addEventListener(MouseEvent.CLICK, createSnapshot);

    function createSnapshot(event:MouseEvent):void {
    imgBD = new BitmapData(video.width,video.height);
    imgBD.draw(video);
    imgBitmap=new Bitmap(imgBD);
    addChild(imgBitmap);
    }

    removeBtn.addEventListener(MouseEvent.CLICK, removeSnapshot);

    function removeSnapshot(event:MouseEvent):void {
    removeChild(imgBitmap);
    }

    thanks for your help, hope to get from you soon^^


  54. Janet,
    By the looks of your code your setMode() method is setting the image to 320×240

    camera.setMode(320,240,15,true);

    Update that code and you should be good to go.


  55. Hi,
    Wonderful explanation! It makes everything look so simple. What changes can be done if streaming is not required and the video should be recorded and saved at the client end? Also, can it be mixed with a background score as in a karaoke, so that instead of sound, video can be recorded?


  56. hi,

    Thanks for remind me..:) erm…when i click the “shotBtn”….the new captured image appear to be much more smaller compare to the original webcam image, so, how am i going to make the size same as the original webcam image after click the “shotBtn” ? what code should i add on?

    below are the scripts:

    var bandwidth:int = 0;
    var quality:int = 100;
    var camera:Camera = Camera.getCamera();
    camera.setQuality(bandwidth, quality);
    camera.setMode(800,600,15,true);
    var video:Video = new Video();

    video.width = 800;
    video.height = 600;
    addChild(video);

    video.attachCamera(camera);
    addChild(video)

    var imgBD:BitmapData;
    var imgBitmap:Bitmap;

    shotBtn.addEventListener(MouseEvent.CLICK, createSnapshot);

    function createSnapshot(event:MouseEvent):void {
    imgBD = new BitmapData(video.width,video.height);
    imgBD.draw(video);

    imgBitmap=new Bitmap(imgBD);

    addChild(imgBitmap);
    }

    removeBtn.addEventListener(MouseEvent.CLICK, removeSnapshot);

    function removeSnapshot(event:MouseEvent):void {
    removeChild(imgBitmap);
    }

    thanks for your help^^


  57. Nice tutorial. Thanks.


  58. Hi. Your explanation is excellent!
    I want to know how to preview 2 or more camera objects at the same time because I am creating a live video routing project at university.
    Please help. Thanks.^^


  59. Can i get camera in 16:9 dimensions plz help


  60. I have a red5 server and would also like to have this webcam function. Can someone please help me? Pay for the completion …


  61. please camera choosing from list
    script pls


  1. 3 Trackback(s)

  2. Edd’s progress – Webcam Code… « BearCanvas
  3. Configurando uma webcam em Actionscript 3 | Dalaz
  4. Configurando uma webcam em Actionscript 3 | Dalaz.com.br

Post a Comment