4

I need to integrate a video stream from my Macbook camera using a Xamarin.Mac form. However, all of the documentation that I find only tells you how to do so in iOS and Android platforms.

How would you go at getting a video stream from a Macbook then? Any libraries I should look at?

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
net30
  • 197
  • 1
  • 11

1 Answers1

6

You will want to review the AVFoundation APIs (QTKit is deprecated).

You can create a custom Xamarin.Forms View renderer based on a NSView and assign the AVCaptureVideoPreviewLayer as the control's layer to stream the camera output to this control.

Store class level references to following and make sure you Dispose them when your control goes out of scope otherwise there will be leaks:

AVCaptureDevice device;
AVCaptureDeviceInput input;
AVCaptureStillImageOutput output;
AVCaptureSession session;

In your capture setup, you can grab the default AV device assuming you want to use the build-in FaceTime Camera (also known as iSight).

macOS/Forms Example:

device = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Video);
input = AVCaptureDeviceInput.FromDevice(device, out var error);
if (error == null)
{
    session = new AVCaptureSession();
    session.AddInput(input);
    session.SessionPreset = AVCaptureSession.PresetPhoto;
    var previewLayer = AVCaptureVideoPreviewLayer.FromSession(session);
    previewLayer.Frame = Control.Bounds;
    Control.Layer = previewLayer;
    output = new AVCaptureStillImageOutput();
    session.AddOutput(output);
    session.StartRunning();
}

enter image description here

Note: A lot of the AVFoundation framework is shared between iOS and MacOS, but there are some differences so if you end up looking at iOS sample code be aware you might need to alter it for macOS.

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • Hi SushiHangover, do you have a github repo or something for your source code ? I am new to xamarin would be nice to have some sample to follow. Thanks – Yini May 10 '19 at 20:37
  • @Yini I doubt I still have that example around after 1.5 years, but if I find it later, I'll send you another comment... – SushiHangover May 10 '19 at 21:40
  • Thanks! I'll try to do up a hack myself see how it goes. – Yini May 11 '19 at 22:59
  • hey thanks for looking into it. I've decided to install windows on Mac and access webcam from there. – Yini May 16 '19 at 21:33
  • 1
    Would be great to have this solution implemented in Xamarin.Forms.macOS – Amir Hajiha Aug 24 '19 at 13:53
  • 1
    @AmirNo-Family That code sample was from a Xamarin.Forms project, using a custom Forms' View renderer. – SushiHangover Aug 24 '19 at 19:03