private void PrepareAndStartCamera()
        {
            _camera.StopPreview();

            var display = _activity.WindowManager.DefaultDisplay;

            if (display.Rotation == SurfaceOrientation.Rotation0)
            {
                _camera.SetDisplayOrientation(90);
            }

            if (display.Rotation == SurfaceOrientation.Rotation270)
            {
                _camera.SetDisplayOrientation(180);
            }

            _camera.StartPreview();

            _timer = new Timer(async state =>
            {
                var image       = _textureView.Bitmap;
                var imageStream = new MemoryStream();
                await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
                image.Recycle();

                NewFrameCaptured?.Invoke(this, new NewFrameEventArgs(new Models.VideoFrame
                {
                    ImageBytes = imageStream.ToArray(),
                    Timestamp  = DateTime.Now
                }));

                imageStream.Dispose();
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(0.5));
        }
Example #2
0
        private async Task StartPreviewAsync()
        {
            // Prevent the device from sleeping while the preview is running
            _displayRequest.RequestActive();

            // Setup preview source in UI and mirror if required
            VideoCapture.Source        = _mediaCapture;
            VideoCapture.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

            this.VideoProperties = this._mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

            // Start preview
            await _mediaCapture.StartPreviewAsync();

            _isPreviewing = true;

            if (_isPreviewing)
            {
                await SetPreviewRotationAsync();
            }

            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(0.5)
            };
            _timer.Tick += async(sender, o) =>
            {
                if (_mediaCapture == null)
                {
                    return;
                }

                const BitmapPixelFormat inputPixelFormat = BitmapPixelFormat.Bgra8;
                var previewFrame = new Windows.Media.VideoFrame(inputPixelFormat, CameraResolutionWidth, CameraResolutionHeight);
                await _mediaCapture.GetPreviewFrameAsync(previewFrame);

                var imageBytes = await GetPixelBytesFromSoftwareBitmapAsync(previewFrame.SoftwareBitmap);

                NewFrameCaptured?.Invoke(this, new NewFrameEventArgs(new Models.VideoFrame()
                {
                    ImageBytes = imageBytes,
                    Timestamp  = DateTime.Now
                }));

                previewFrame.Dispose();
            };
            _timer.Start();
        }