Displaying a webcam’s video in a Flex VideoDisplay control

by Peter deHaan on January 22, 2008

in Camera,VideoDisplay

The following example shows you how you can display a user’s webcam feed in a VideoDisplay control using the static Camera.getCamera() method and VideoDisplay class’s attachCamera() method.

Full code after the jump.

This example won’t be very interesting unless you actually have a webcam installed.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/01/22/displaying-a-webcams-video-in-a-flex-videodisplay-control/ -->
<mx:Application name="VideoDisplay_attachCamera_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
 
            private function videoDisplay_creationComplete():void {
                var camera:Camera = Camera.getCamera();
                if (camera) {
                    videoDisplay.attachCamera(camera);
                } else {
                    Alert.show("You don't seem to have a camera.");
                }
            }
        ]]>
    </mx:Script>
 
    <mx:VideoDisplay id="videoDisplay"
            creationComplete="videoDisplay_creationComplete();"
            width="160"
            height="120" />
 
    <mx:Button id="button"
            label="Reload Camera"
            click="videoDisplay_creationComplete();" />
 
</mx:Application>

View source is enabled in the following example.

{ 51 comments… read them below or add one }

1 barry.b January 23, 2008 at 5:16 am

the else “Alert.show(“You don’t seem to have a camera.”);” isn’t working (Mac OS-X 10.4 iBook PPC – mic but no camera). got prompted to give permissions to access the webcam/microphone though

Reply

2 Matt Platte January 23, 2008 at 9:30 am

Right-click the Flash movie, choose Settings.

My Macbook will usually try to open “DV Video” instead of the iSight camera which is “USB Video Class Video”. I suppose there’s a way to make USB the default but I haven’t searched for that.

Reply

3 barry.b January 25, 2008 at 5:50 am

@Matt. thanx (that actually helped getting a Mac camera working with Connect/Breeze)

but for my iBook (no built-in iSight camera, no camera plugged in at all) all I’m saying is that the “else” doesn’t fire

(selecting which camera won’t work … since there isn’t one at all)

Reply

4 peterd January 25, 2008 at 8:25 am

barry.b,

What happens if you compile and run the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">
 
    <mx:Script>
        <![CDATA[
            import flash.media.Camera;
            import mx.utils.ObjectUtil;
 
            private var camera:Camera;
 
            private function init():void {
                camera = Camera.getCamera();
                textArea.text = ObjectUtil.toString(camera);
            }
        ]]>
    </mx:Script>
 
    <mx:Label text="{Camera.names} ({Camera.names.length})" />
    <mx:TextArea id="textArea"
            editable="false"
            width="100%"
            height="100%" />
 
</mx:Application>

Reply

5 peterd January 25, 2008 at 10:44 am

barry.b,

Actually, I quickly converted this into a new entry. Can you check out “Getting specific camera instances using the static Camera.getCamera() method” and tell me what you see?

On my IBM laptop w/ my USB “Logitech QuickCam Express”, I only see one installed camera (my laptop doesn’t have a built-webcam). However, on my iMac w/ built-in iSight, I see three cameras: “DV Video”, “IIDC Firewire Video”, and “USB Video Class Video”.

Peter

Reply

6 barry.b January 27, 2008 at 5:24 am

“However, on my iMac w/ built-in iSight, I see three cameras: “DV Video”, “IIDC Firewire Video”, and “USB Video Class Video”.”

as do I, with no camera attached. I also get the same three options when using Connect (Breeze) and “select a camera”.

is it significant that all three settings show “activityLevel = -1″

Perhaps this is OS X being wishful in it’s thinking? the OS provides a generic three drivers whether the machine it’s installed on has the device or not?

I haven’t been using Mac’s with/without webcams for long, but gut feeling might be an old limitation between Flash and OS X coming back to haunt.

Bottom line however could be that there’s only a test for suitable Mac camera drivers but not the the device itself to be installed and functional. But I’m just guessing…

Reply

7 s March 14, 2008 at 1:58 pm

Hi,

I have some xmls stored in various date folders by the name of yyyymmdd on unix. I have a flex page that that has plots which source data from these xmls using a jsp that has out.println for the xml i want to source. I call this jsp using HTTPSERVICE. I have a datechooser to chose a date depending on which I want to source the xml fromt he folder which depends on the date selected. So, my question is is there a way to reload a flex page with parameters?After choosing a date I want to add this date to the param list passed to the jsp..and I want to refresh my charts with this new jsp url..
I tried javascript:location.reload(true) but it refreshes the page with default date value i.e it doesn;t persist the date value i selected last using the date selector. Please help

Thanks

Reply

8 Tim Perrett March 15, 2008 at 12:02 pm

Out of interest, is there a way to capture a still image from the webcam?

Cheers

Tim

PS: great useful article!!

Reply

9 sudheer April 16, 2008 at 10:35 am

Sorry it doesnt work for me….it just shows a dark screen, my web cam software clearly captures the video flex is unable to that….

Reply

10 usb dani May 2, 2008 at 6:45 am

A very nice example for my Webcam – works for me. Thanks a lot!

Reply

11 Webcam May 18, 2008 at 10:23 am

Thanx this helped me a lot and lucky me that have a brand new webcam :)

Reply

12 kevin May 31, 2008 at 4:56 pm

Hi,
I have two webcam setup on my PC. Please let me know how to detect all webcams and let the user select one of them.

Thanks for the tutorials/examples.

Reply

13 peterd May 31, 2008 at 11:15 pm
14 kevin June 1, 2008 at 5:44 am

Awesome! Thank you. I really love your examples. Have a great day.

Reply

15 andrelau June 28, 2008 at 11:25 am

It looks like it cannot get the ‘stream’ from a DV camcorder connected. But ! it shows it in the list. I checked with http://www.acrobat.com and the cam does not work too.

Reply

16 darek October 1, 2008 at 12:34 am

hi is it possible to connect hdcam using flex? we are working with livestreaming tv application and we would like to add a new feature like live match transmition or live web conferences. so I’m asking is there possibiliity to connect hdcam I now that with web cam’s there is no problem but I can’t get any information how to connect to hdcam. Thx for answer

Reply

17 Morad November 11, 2008 at 12:15 pm

This is great! But the only thing, how about the audio/microphone?

And, the main thing is that I was wondering about. Is there a possibility to record video/audio from microphone?

Your feedback is much appreciated.

Reply

18 Bill November 16, 2008 at 1:30 pm

Great example. One thing to clarify. I have a MacBook and tried to get this working but no luck. The default camera instance it chose was wrong. I used your example on getting specific instances and this showed me 3 cameras that Mac OS X thought I had. I tried using each name in succession in a loop to try to attach. No luck. Then I read the documentation on the Camera class and the light bulb went off. You have to specify the index of the camera in the returned array and NOT the name as you would think. And this is really goofy, you have to specify the index as a string. For example, my Camera.names invocation returned the following array:
DV Video
IIDC FireWire Video
USB Video Class Video

The way to invoke the USB camera is:

camera = Camera.getCamera("2");

Reply

19 Cheng November 18, 2009 at 9:18 am

This works for my MBP! Thanks a lot!

Reply

20 rajkumar November 26, 2008 at 11:29 pm

This article is very good,i need to capture that video stream and my total application will be at server side.At the client side only connect the USB camera and capture his image.Is it possible for to me,please clarify my doubt.

Reply

21 Santosh Bhoyar January 9, 2009 at 1:59 am
nc.connect( "rtmp://localhost:1935/" );
mic = Microphone.getMicrophone();
nc.addEventListener( NetStatusEvent.NET_STATUS, onStatus );
}
 
public function onStatus( e:Event ):void {
    publish_ns = new NetStream( nc );
    cam = Camera.getCamera();
    cam.setQuality( 0, 100 );
    publish_ns.attachCamera( cam );
    publish_ns.attachAudio( mic );
    webCam.attachCamera( cam );
}
 
private function startRecording():void {
    recLabel.visible=true;
    start.visible=false;
    stop.visible=true;
    var fileName:String = "SantoshBhoyar_"+String(Math.random());
    publish_ns.publish( fileName, "record" );
}

Reply

22 manisha April 15, 2010 at 3:32 am

Santosh Bhoyar,, Thank you so much for your help. Its working for me. Santosh bhoyar, Can you help me to build my web conference application ?

Reply

23 Santosh Bhoyar January 9, 2009 at 1:56 am

Hi,
Here are the sample code to capture the video and save it on the server side using Flash Media Server.

Reply

24 Torgeir January 20, 2009 at 11:35 pm

Great example, perfect.
Try setMode() to change resolution and fps for your camera..

camera.setMode(640, 480, 15);

Best Regards,
Torgeir

Reply

25 Darshan March 9, 2009 at 12:19 pm

Plz santosh will you publish full code for capturing and Recording is it possible with Red5 server
plz do me reply @ darshanshah87@gmail.com

Reply

26 paktua March 10, 2009 at 1:12 pm

can i catch several webcam in once? what i mean is can il make like video conference using flex? example there 5 user online, so it will get 5 different webcam and show it in one page.

thank you,

paktua

Reply

27 Bernard Jason Berras April 17, 2009 at 6:39 pm

actually Santosh Bhoyar already answer ur question just add a record button that will trigger startrecording :)

Reply

28 DJ April 23, 2009 at 4:22 am

Hello peter,

Thank for the example. Its very useful. I have added a record function to the application that records the webcam stream. Everyting works fine.

The next thing i´m try to accomplish is to capture the screen (website screen capturing) and turn that into a video.
I have looked at you Imagescreen capture tutorial and i was hoping it would be something simulare for video.
Do you know how to accomplish that?
Can anyone help me out?

Thankx

Happy flexing everybody.

Reply

29 Santosh Bhoyar June 10, 2009 at 8:06 am

Hi,

I have worked on same module and I finally concluded that FFMPEG will be perfect utility for this job. Its free and open source,, U can utilise in ur application in server side.. I am sure , it will help !

Reply

30 Madhan K June 23, 2009 at 9:47 pm

Hi,
Nice article. And is it possible for us to extend this to video chat kind of application ?

Reply

31 Lorena Bonita August 3, 2009 at 7:56 am

Hello,

Great example. thanks.

But how to capture an image using the example?

Reply

32 Alex Fisherr August 4, 2009 at 10:18 pm

Hi,
I want to control the access of webcam when the application starts. For example, when the application starts, it asks for the permission in a pop up. When it is allowed, every thing works fine. But what if user denies that pop up. I handle the event in CamStatus Event and every thing works well there. But the pop never appears again if Camera.getCamera() method is called. One must restart the application and the permission pop up comes only once in the start.
Can any one suggest me how to get that popUp appear every time when user clicks on a button, say “Load Camera”, and if it is denied the access, it comes again everytime the button is pressed and finally connected once user “allows” the camera to be opened

Reply

33 Jay Wood February 5, 2010 at 11:47 am

Alex,

This may be too late to be of any use to you, but perhaps it will help someone else reading this post.

When you call attachCamera(), Flex will display the pop-up only if it does not already have a decision from the user (either allowing or denying access). To take control of this in your code, simply check for permission before calling attachCamera(). If permission is lacking, you can then request the Flash pop-uop by calling Security.showSettings(SecurityPanel.PRIVACY), and listen for a StatusEvent that gets dispatched when the user clicks “Allow” on the pop-up.

Below is an excerpt of the sample code at the top of this blog post, with my changes in bold (I’ve omitted the MXML so it doesn’t get eaten by the blog):

import mx.controls.Alert;

import flash.system.Security;
import flash.system.SecurityPanel;
import flash.events.StatusEvent;

private function videoDisplay_creationComplete():void {
var camera:Camera = Camera.getCamera();
if (camera) {

if (camera.muted) { // need access permission
camera.addEventListener(StatusEvent.STATUS, onAccessGranted);
Security.showSettings(SecurityPanel.PRIVACY);
} else {

videoDisplay.attachCamera(camera);

}

} else {
Alert.show("You don't seem to have a camera.");
}
}

private function onAccessGranted(event:StatusEvent):void {
event.target.removeEventListener(event.type, onAccessGranted);
if (event.code == "Camera.Unmuted") {
videoDisplay.attachCamera(camera);
} else {
Alert.show("You have not given permission to use the camera.";
// NOTE: contrary to the Flex API docs, I found that StatusEvent is NOT dispatched when the user clicks "deny", only when
// they click "allow"... so in reality you would never see this Alert.
// Also, there seems to be no way of detecting when the user dismisses the pop-up. Blech.
}

Reply

34 Dyke Iloghalu May 31, 2010 at 2:40 am

“I’ve omitted the MXML so it doesn’t get eaten by the blog”

Thanks for your great post. It was very useful. I am very new in video conferencing. You said that you omited MXML (I know xml a little but I know nothing about MXML).

I will be very greatful if you can mail the MXML to me via email in text file, so that I can test your script
My email address is dyke_iloghalu@yahoo.com

35 Bry August 16, 2009 at 1:36 am

Is it possible to get better resolution when scaling the webcam display? I changed the display size to 800×600 and the resolution is terrible. I am sure it is not my webcam as it provides 3mp capturing.

Thanks for the source code!

Reply

36 Peter deHaan August 16, 2009 at 7:06 am

@Bry,

I don’t have a webcam at home (and I only have a super-cheap Logitech webcam at the office), but Torgeir’s earlier comment suggests calling the setMode() method to change resolution and fps for your camera:

camera.setMode(640, 480, 15);

Peter

Reply

37 Bry August 29, 2009 at 10:57 pm

Can you give me an example of this code within the source code given above? I am new with flex and always get an error at this point. Thanks for the help!

Reply

38 Mario October 17, 2009 at 8:59 am

This example works when I use it from this webpage but when I try to build it as a flex project in my computer it only shows a black screen with no video. I don’t know why is doing that, does anybody have an idea why is this happening?

Thanks

Reply

39 Venkat December 15, 2009 at 11:00 pm

Hello santosh,
How can i connect my digital camera in flex and then how can i record the particular part of the video in the digi cam.

thanks in advance

Reply

40 Matbaa December 18, 2009 at 5:58 am

Hello, I wonder If can we turn this app to video conference?

Reply

41 Santosh Bhoyar, Hyderabad April 12, 2010 at 4:58 am

Matbaa,
Yes, you can apart from that , need few more easy stuff to do.
For Video Conference , you need the Media streaming server. I have worked on Red 5 Server and Flash media Server.
Please let me know which one you are using, accordingly I will help you to build video conference application in Flex…

Regards,
Santosh Bhoyar, hyderabad

Reply

42 The House of Husar December 21, 2009 at 8:07 pm

Any reason why this doesn’t work when setting up a Air app in Flex and not not browser delivery?

Thanks.

Reply

43 rave February 19, 2010 at 2:42 am

hi, i’ve the same problem…. i can see this example working on this website, but when i past it in a new project of mine and run it…i just get a black background with no image…

i do get the Security alert, and give access to it..but then…theres is no capturing :(

any ideas ?

thanks in advance..

Reply

44 rave February 19, 2010 at 2:51 am

Ok i’ve found my problem…
For an unknown reason i do have an old-school Creative NX Ultra Webcam only….but have two “diferent” drivers installed for the same cam.

“NX Ultra” and “NX Ultra (VFW)” ….

So , to get the example locally going i’ve set the Camera.getCamera() to “1″ -> Camera.getCamera(“1″);

and voila! ;)

Stay Fresh!

Reply

45 Boldis Media April 1, 2010 at 7:13 am

Thanks a lot! Exactly what I’m looking for social web portal in Russia!

Reply

46 edner April 9, 2010 at 5:18 am

Good example.

Is there any complete source code example that show how to create a video conference or video chat??
If not how should i proceed?

Thanks.

Reply

47 info2basha May 25, 2010 at 12:10 pm

Hi,

I have seen the same kind of requirement in VB.Net programmin, the recording of video .avi takes up large amount of disk space and can fill up the hard disk storage pretty quickly. As an example, a 37-second clip took up 66MB of disk space.

Can anybody tell me how about this in Flex.

Thank You.

Reply

48 Anonymous June 3, 2010 at 7:21 am

Hi Santhosh Bhoyar,

I am new to Flex Programming. I was trying to run your code also with the code given at the top of this posting and I am getting errors. Can you please help me to resolve this.

Thank You.
Basha

Reply

49 Basha June 3, 2010 at 7:26 am

&ltmx:Application name=”WebCamCapture”
xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”vertical”
verticalAlign=”middle”
backgroundColor=”white”&gt

&ltmx:Script&gt
&lt![CDATA[
import mx.controls.Alert;
import flash.system.SecurityPanel;
import flash.events.StatusEvent;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.utils.ByteArray;

var camera:Camera = Camera.getCamera();
// var microphone:Microphone = Microphone.getMicrophone();
// var nc:NetConnection = new NetConnection();
// var publish_ns:NetStream = new NetStream(nc);
//nc.addEventListener( NetStatusEvent.NET_STATUS, onStatus );
// nc.connect( "rtmp://localhost:1935/" );

private function videoDisplay_creationComplete():void {

if (camera) {
videoDisplay.attachCamera(camera);
if (camera.muted)
{
camera.addEventListener(StatusEvent.STATUS, onAccessGranted);
Security.showSettings(SecurityPanel.PRIVACY);
}
else
{
videoDisplay.attachCamera(camera);
}
} else {
Alert.show("You don't seem to have a camera.");
}
}

private function onAccessGranted(event:StatusEvent):void {
event.target.removeEventListener(event.type, onAccessGranted);
if (event.code == "Camera.Unmuted") {
videoDisplay.attachCamera(camera);
} else
{
Alert.show("You have not given permission to use the camera.");
}

//public function onStatus( e:Event ):void {
// publish_ns = new NetStream( nc );
// camera = Camera.getCamera();
// camera.setQuality( 0, 100 );
// publish_ns.attachCamera( camera );
// publish_ns.attachAudio( microphone );
// webCam.attachCamera( camera );
//}

//private function startRecording():void {
// recLabel.visible=true;
// start.visible=false;
// stop.visible=true;
// var fileName:String = "SantoshBhoyar_"+String(Math.random());
// publish_ns.publish( fileName, "record" );
//}

}

]]&gt
&lt/mx:Script&gt

&ltmx:VideoDisplay id=”videoDisplay”
creationComplete=”videoDisplay_creationComplete();”
width=”40%”
height=”40%” /&gt
&ltmx:Label text=”{Camera.names} ({Camera.names.length})” /&gt

&ltmx:Button id=”button”
label=”Reload Camera”
click=”videoDisplay_creationComplete();” /&gt

&ltmx:Button id=”button2″
label=”start”
click=”videoDisplay_creationComplete();” /&gt

&ltmx:Button id=”button3″
label=”stop”
click=”videoDisplay_creationComplete();” /&gt

&lt/mx:Application&gt

Reply

50 jerryNguyen June 10, 2010 at 2:38 am

i have two webcam. I want to show them on an application. I use Camera.names method to return an array of indexs string of webcam. My app run ok on IE but Fifox not ok.
Thank

Reply

51 Wow July 23, 2010 at 7:43 pm

me2! if i disable one of my camera, it works, but i don’t konw why it can not work

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: