:: AForge.NET Framework :: Articles :: Forums ::

Reconnecting webcam after USB disconnect

Forum to discuss AForge.NET Framework, its features, API, how-tos, etc.

Reconnecting webcam after USB disconnect

Postby bgampert » Mon Nov 19, 2018 7:36 pm

Hello Andrew,

I'm working on a project with a USB webcam using the Video->Snapshot Maker sample as a starting point. The sample runs well but I'd like my app to be able to handle the user unplugging the USB webcam, and then be able to reconnect to the video stream when it is plugged back in.

I have not been successful so far with my attempts. I subscribe to the VideoDevice_PlayingFinished event and it fires with the ReasonToFinishPlaying.DeviceLost as expected. But I am not clear on any operations that need to be performed on the existing videoDevice object or videoSourcePlayer at that point, and whether or not there needs to be a new instance of the videoDevice when plugged back in.

I appreciate any guidance, and thank you in advance!
Posts: 1
Joined: Mon Nov 19, 2018 6:30 pm

Re: Reconnecting webcam after USB disconnect

Postby andrew.kirillov » Tue Nov 20, 2018 9:20 am

Hello Bob,

There are few possible solutions. The best one might be to monitor for USB events and try starting a camera when something (if you can check if it is camera, then even better) is plugged into USB socket. You don't need to create new instance of the video source, just call its Start() method again. USB events is something out of scope for the AForge.NET Framework, so this part you may need to research.

In another project I did, the video source does not stop at all when device is unplugged. It will notify caller about the error, but the video acquisition loop does not stop. Instead it will make a pause for a second or so and then it will try connecting back to the camera, again and again. Not perfect, but does the job. Here is the C++ code implementing this solution. If you would like to implement such solution, then it would require change in AForge.NET Framework's code.

If you don't want to mess with the AForge.NET code, you can implement similar on your side. Just call Start() method periodically until eventually you start getting NewFrame events.
With best regards,

Interested in supporting AForge.NET Framework?
User avatar
Site Admin, AForge.NET Developer
Posts: 3453
Joined: Fri Jan 23, 2009 9:12 am
Location: UK

Return to AForge.NET Framework