Search code examples
c#macosxamarinmonomac

Xamarin MonoMac preview webcam onto Main Window ( AVCaptureVideoPreviewLayer )


I created a simple Xamarin MonoMac Mac application ( bare bones 1 window ). I am trying to get a preview of my webcam onto the Main Window of the application. I use the AVFoundation classes to get access to the webcam.

I can successfully connect to the mac's webcam, and the webcam light turns on but I get no video on the Main Window.

My c# code

        session = new AVCaptureSession () { SessionPreset = AVCaptureSession.PresetMedium };

        var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);

        var input = AVCaptureDeviceInput.FromDevice (captureDevice);
        if (input == null){
            Console.WriteLine ("No input - this won't work on the simulator, try a physical device");

        }

        session.AddInput (input);

        AVCaptureVideoPreviewLayer captureVideoPreviewLayer = new AVCaptureVideoPreviewLayer (session);

        **//----> preview layer onto Window here ?!**

        session.StartRunning ();

Solution

  • This fixed it - hopefully it will help someone ..

                AVCaptureVideoPreviewLayer captureVideoPreviewLayer = AVCaptureVideoPreviewLayer.FromSession (session);
    
                this.Window.ContentView.Layer=captureVideoPreviewLayer;
                this.Window.ContentView.WantsLayer=true;
    
                session.StartRunning ();