Use your webcam with the WP7 Emulator (with code!)

The GPS Simulator seemed pretty popular with many developers and whilst I was browsing through various forums, I noticed the request for webcam usage as the emulator’s camera. In an earlier project (using the April CTP), I needed to be able to use the webcam as well as the ability to use images from within the application. The latter spawned the Testing Photos with WP7 Emulator post, but I could see no way to use my webcam as the camera. Well now (literally 10 minutes after coming up with the idea – that’s what happens when you have awesome dev tools ;)), I simply re-factored the GPS Sim code and have it working for a webcam instead of Bing maps. What PicSim allows you to do is to use your webcam to capture an image and then immediately have that image streamed over to your WP7 application, as well as other images stored on your computer. You can download the source code and see a screenshot below.

A few things to note:

Firstly, there’s no direct interface to webcams (AFAIK) in .NET. There are various libraries out there that allow you to access the user’s webcam, but I decided to follow this method and use the commonly found avicap32.dll library. This DLL file is found in most System32 folders so hopefully you’ll already have it :). I’ve slightly modified the WebCam class from that site because it was saving the image out to a file instead of a MemoryStream. I also suppressed a popup on line 105 (in case you need to debug) which kept coming up even though the program was running fine.

Secondly, there is no error handling or anything. As I say, it was a quick 10 minute re-factor of the GPS Sim. In order to get it working, simply take the picture (or load one from your computer) and click on the relevant “send image” button. Then, from the WP7 app, simply click on Load Image and hopefully the image will show within the app  (as shown by the recursive image below). All the images are converted to JPEG format, but you can change that in the source.

The download has one zip file which contains one solution hosting both projects. You can run both projects from VS2010 for Windows Phone Beta (simply load the solution). The PicSim Consumer app is a WP7 app demonstrating how to get the image, so you can simply apply the same method in your WP7 apps.

Hope this is useful for your development!

Download the source code

Retweet This Post

@keyboardP

Share

38 Responses to Use your webcam with the WP7 Emulator (with code!)

  1. Pingback: Tweets that mention Use your webcam with the WP7 Emulator (with code!) « Phone 7 -- Topsy.com

  2. Pretty nice development !

  3. Jeff Fansler says:

    This looks pretty cool. I’d like to review the source, but when I try to download I just get a blank page. I tried with both IE8 and Firefox 3.6.3.

  4. Jeff Fansler says:

    Hey KeyboardP,
    Sorry to bug you but I think there’s one more problem. The PicSim Consumer project appears to be a default WP7 project. I don’t see any new xaml or code in MainPage.xaml. The PicSim project runs and I can get content from my webcam.

    Also, a side note. At least on Windows 7, you need to run Visual Studio as an administrator so the ServiceHost can open a port.

    -Jeff

  5. Jeff Fansler says:

    Thanks keyboardP,
    The download works and so does the code. Good job!

  6. Pingback: Webcam im Windows Phone 7 Emulator benutzen | Smartphones mit Windows Phone 7

  7. MKRAC says:

    First I send Thanks for you effort. And now the question:

    When trying to run the picsim on my Windows 7 64 bit machine I always get an an AddressAccessDeniedException when the host.Open call should be executed. I pasted the exception here. It says that the URL could not be registered ad the Process has not the right to do so. I switched to my local admin account, but still the same issue :-(. How to solve this one ?!?!?

    System.ServiceModel.AddressAccessDeniedException was unhandled
    Message=HTTP konnte URL “http://+:8000/PicSim/” nicht registrieren. Der Prozess weist keine Zugriffsrechte für diesen Namespace auf (Details finden Sie unter hhttp://go.microsoft.com/fwlink/?LinkId=70353).
    Source=System.ServiceModel
    StackTrace:
    bei System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
    bei System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
    bei System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
    bei System.ServiceModel.Channels.TransportChannelListener.OnOpen(TimeSpan timeout)
    bei System.ServiceModel.Channels.HttpChannelListener.OnOpen(TimeSpan timeout)
    bei System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
    bei System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
    bei System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
    bei System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
    bei System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
    bei System.ServiceModel.Channels.CommunicationObject.Open()
    bei PicSim.Program.Main() in C:\Users\kremer\Documents\Visual Studio 2010\Projects\PicSim Consumer\PicSim\Program.cs:Zeile 62.
    bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    bei System.Threading.ThreadHelper.ThreadStart()
    InnerException: System.Net.HttpListenerException
    Message=Zugriff verweigert
    Source=System
    ErrorCode=5
    NativeErrorCode=5
    StackTrace:
    bei System.Net.HttpListener.AddAllPrefixes()
    bei System.Net.HttpListener.Start()
    bei System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
    InnerException:

    • keyboardP says:

      Hi,
      If you’re running as an admin, it should work. Have a read of this blog post and let me know if that fixes the issue.

      • MKRAC says:

        Yehaaw, right click on Visual Studio and “Run as Admin” solved the issue. Hey that works perfectly.
        Just a short question. Im developing a barcode reader from scratch for my employer As the WP7 emulator lacks a working built in cam solution am I allowed to use your code for our software for debugging and testing as long as Microsoft does not provide working solutions ?

      • keyboardP says:

        Glad you got it sorted, thanks for getting back. I’m guessing MS may make this feature standard in the emulator some time down the line, but until then (even after, if you want to), you’re free to use the code in your projects, however you like 🙂

  8. mine still doesn’t work. see the exception below. I’m using VS 2010 Express for windows phone. Also I’m running VS as administrator.

    The type ‘Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior, Microsoft.VisualStudio.Diagnostics.ServiceModelSink, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ registered for extension ‘Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior’ could not be loaded. (C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config line 232)

    It appears that this line throw the error :

    ServiceHost host = new ServiceHost(typeof(Picsim), baseAddress);

    • keyboardP says:

      Hi Murad,
      I can confirm that it works with the RTM version of the development tools without any modifications. I can’t reproduce this error, so I can’t test if this works. However, I assume you have .NET 4 installed already (and thus the directory “C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\” does exist. If so, then open up machine.config in that directory. Search for ‘sink’ and there should be a line similar to this:
      <add name="Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior" type="Microsoft.VisualStudio.....

      Comment out that line, save the file and then try again. I believe the ServiceModelSink assembly is used to debug WCF services.

  9. Hi keyboardP.

    your solution works for me now. many many thanks 🙂

  10. Pingback: Oleksandr Krakovetskiy blog

  11. Pingback: 超快递 beta版 » Windows Phone 7 资源汇总(超全)

  12. Hi KeyboardP,

    long time ago i wrote you (MKRAC ;)). How ‘r’ u? He He im currently testing a bit with mango and of course MS did not realize the WebCam Feature within the emulator :(. I want to do some AR stuff now, so it would be great to have a video stream i could use instead of a single image.

    If you allow, i’ll try to modify your solution, so that it sends a complete video stream which can be used for AR Apps within the emulator.

    Do you have som kind of Mail/Messenger if I have any questions ?

    Cheers,
    Markus

    • keyboardP says:

      Hi Markus!

      You’re more than welcome to mess around with the code and see what you can get. I haven’t had a chance to play around with the Mango tools as I’m having some trouble with installation (won’t deploy to emulator :(), so I won’t be much use there. However, if you do have a question, I’ll try my best to answer. You can email me (phone7 [at] live [dot] co [dot] uk). Of course, if you get something working, let me know and I’ll create a new blog post about it 🙂

      Good luck!

  13. harish says:

    whlle i run the downloaded project “HTTP could not register URL http://+:8000/PicSim/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).” ………………… Please help

    • keyboardP says:

      Hi Harish,
      You need to run it as Administrator so that you have permission. Try right clicking on Visual Studio and select ‘Run As Administrator’.

  14. Harish says:

    Hi Harish,
    You need to run it as Administrator so that you have permission. Try right clicking on Visual Studio and select ‘Run As Administrator’.

    Thanks ………. It is working now :))))

  15. netita says:

    Hello;

    First of all, great work and resource for me. many thanks.

    May I ask that why did you use WCF in this project except the reason the you used WCF in GPSSimulator. What else can we use except wcf?

    • keyboardP says:

      Hi netita, glad you like the work 🙂
      At the time this project came out, developers didn’t have direct access to Sockets (we can now, on Mango). Therefore, in order to get information across a network, I used WCF. Even now, if I had to create this project again, I’d use WCF over Sockets because I don’t need the extra speed that Sockets can provide. If I was doing something a bit more real-time and intensive, then sockets would be a good way of doing it. In this case, WCF makes it easier to send/receive information between the two parts since it hides all the lower level code. However, sockets are an alternative if you don’t want to use WCF.
      Hope that helps!

  16. rissé says:

    hi there. fof many thanks for the sample. 🙂 I ran the code for one it seem very well but after this something strange happens when i run the code again. A window is being opened and ask me for choosing a cam device from the list it gives to me. List contains only my hp’s entegrated cam-which is the only device I have- so i choose it, and press OK. then wpf is opened but there is no video image on the picture box. This state doesnt change until i restart the pc. :S How can i fix it, do u have any idea??

    • keyboardP says:

      Hi,

      I’m sorry, I’ve never come across this problem. It may be something to do with your webcam driver. Try reinstalling or updating it from the manufacturer’s website. Also, make sure you’re running Visual Studio as administrator.

  17. rissé says:

    Hi there!
    Ive solved my problem with erasing the part of “listing devices”.
    But now, i cannot reach and read what wcf services you read in localhost:8000/PicSim from the browser although i am on admin mode for vs2010?

    • keyboardP says:

      Are you trying to do is straight from the device? Instead of ‘localhost’, try using your local IP address (192.168….) or machine name.

  18. viktor says:

    Hi, is there any way to create an .exe file for this sln(both phone and forms)??

    • keyboardP says:

      Hi. You can create an exe of the form by building it as with any WinForm project. Once you build it, you can find in the ‘bin/debug’ or ‘bin/release’ folder in the project’s directory. The phone client cannot be converted into a standalone exe, but you can build it in the same way to create a XAP file. This XAP file can then be loaded onto your phone, as long as your phone is developer unlocked.

Leave a reply to keyboardP Cancel reply