Exemplo n.º 1
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
     {
         // 隱藏系統欄
         await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
         // 強制頁面水平
         Windows.Graphics.Display.DisplayInformation.AutoRotationPreferences = Windows.Graphics.Display.DisplayOrientations.Landscape;
     }
     // 開始預覽
     await _capture.StartPreviewAsync();
 }
        public async Task LoadDataAsync()
        {
            Message = "Loading Data..";

            // Check if face group alredy exists, otherwise create it.
            try
            {
                await faceClient.GetPersonGroupAsync(Settings.PersonGroupId);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode == "PersonGroupNotFound")
                {
                    await faceClient.CreatePersonGroupAsync(Settings.PersonGroupId, Settings.PersonGroupId);
                }
                else
                {
                    throw;
                }
            }

            currentEvent = await meetupService.GetCurrentEventAsync();

            if (currentEvent == null)
            {
                Message = "No event scheduled.";
                return;
            }

            registeredPersons = (await faceClient.GetPersonsAsync(Settings.PersonGroupId)).ToList();
            RSVPs             = await meetupService.GetRSVPsAsync(currentEvent.Id);

            // Get comments start with 'Welcome' to track who comes to the event.
            RSVPComments = (await meetupService.GetCommentsAsync(currentEvent.Id)).Where(x => x.CommentDetail.StartsWith("Welcome ")).ToList();

            // Check if RSVPed meetup member is registered to Face API.
            foreach (RSVP rsvp in RSVPs)
            {
                var registeredPerson = registeredPersons.FirstOrDefault(x => x.Name == rsvp.Member.Name);
                if (registeredPerson == null)
                {
                    var userData = new JObject();
                    userData["memberId"] = rsvp.Member.Id;
                    var createdPersonResult = await faceClient.CreatePersonAsync(Settings.PersonGroupId, rsvp.Member.Name, userData.ToString());

                    registeredPersons.Add(await faceClient.GetPersonAsync(Settings.PersonGroupId, createdPersonResult.PersonId));
                }
            }

            await mediaCapture.StartPreviewAsync();

            Identify();
        }
Exemplo n.º 3
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create new MediaCapture
            MyMediaCapture = new MediaCapture();
            await MyMediaCapture.InitializeAsync();

            // Assign to Xaml CaptureElement.Source and start preview
            myCaptureElement.Source = MyMediaCapture;

            // show preview
            await MyMediaCapture.StartPreviewAsync();
        }
Exemplo n.º 4
0
        async private void openCamera(object sender, RoutedEventArgs e)
        {
            if (StartVideo == false)
            {
                //camera.Icon = IconElement.
                if (video_buffer != null)
                {
                    video_buffer.Dispose();
                }
                video_buffer              = new InMemoryRandomAccessStream();
                showVideo.Visibility      = Visibility.Collapsed;
                capturePreview.Visibility = Visibility.Visible;
                //ProfilePic.Visibility = Visibility.Collapsed;
                captureManager_video = new MediaCapture();
                //选择后置摄像头
                var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

                if (cameraDevice == null)
                {
                    System.Diagnostics.Debug.WriteLine("No camera device found!");
                    return;
                }
                var settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    //MediaCategory = MediaCategory.Other,
                    //AudioProcessing = AudioProcessing.Default,
                    //PhotoCaptureSource = PhotoCaptureSource.Photo,
                    AudioDeviceId = string.Empty,
                    VideoDeviceId = cameraDevice.Id
                };
                await captureManager_video.InitializeAsync(settings);

                //摄像头旋转90度
                //captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                capturePreview.Source = captureManager_video;
                // await captureManager_video.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), video_buffer);
                await captureManager_video.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), video_buffer);

                await captureManager_video.StartPreviewAsync();

                //await captureManager_video.StartPreviewAsync();
                StartVideo = true;
            }
            else
            {
                await captureManager_video.StopRecordAsync();

                //SavaVideoToFile();
                SaveToFile(video_buffer, false);
                StartVideo = false;
            }
        }
Exemplo n.º 5
0
        // Button Click event to get media file and load it
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync();

            cePreview.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            detectFaces_Click(sender, e);
            timedCommands();
            await SetLocalMedia();
        }
Exemplo n.º 6
0
 /// <summary>
 /// Asynchronously begins live webcam feed
 /// </summary>
 public async Task StartCameraPreview()
 {
     try
     {
         await mediaCapture.StartPreviewAsync();
     }
     catch
     {
         initialized = false;
         Debug.WriteLine("Failed to start camera preview stream");
     }
 }
Exemplo n.º 7
0
        private async Task StartPreviewWithRotationAsync()
        {
            //<SnippetStartPreviewWithRotationAsync>
            PreviewControl.Source        = mediaCapture;
            PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

            await mediaCapture.StartPreviewAsync();

            await SetPreviewRotationAsync();

            //</SnippetStartPreviewWithRotationAsync>
        }
Exemplo n.º 8
0
        /// <summary>
        /// Event handler for camera source changes
        /// </summary>
        private async Task StartWebCameraAsync()
        {
            try
            {
                if (_captureManager == null ||
                    _captureManager.CameraStreamState == CameraStreamState.Shutdown ||
                    _captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (_captureManager != null)
                    {
                        _captureManager.Dispose();
                    }

                    // Workaround since my home built-in camera does not work as expected, so have to use my LifeCam
                    MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
                    var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    var selectedCamera = allCameras.FirstOrDefault(c => c.Name.Contains("LifeCam")) ?? allCameras.FirstOrDefault();
                    if (selectedCamera != null)
                    {
                        settings.VideoDeviceId = selectedCamera.Id;
                    }
                    //settings.PreviewMediaDescription = new MediaCaptureVideoProfileMediaDescription()

                    _captureManager = new MediaCapture();
                    await _captureManager.InitializeAsync(settings);

                    WebCamCaptureElement.Source = _captureManager;
                }

                if (_captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (_frameProcessingTimer != null)
                    {
                        _frameProcessingTimer.Cancel();
                        _frameProcessingSemaphore.Release();
                    }

                    TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); //15fps
                    _frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);

                    _videoProperties = _captureManager.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

                    await _captureManager.StartPreviewAsync();

                    WebCamCaptureElement.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}");
            }
        }
Exemplo n.º 9
0
        private async void InitializeVideo()
        {
            try
            {
                if (mediaCapture != null)
                {
                    // Cleanup MediaCapture object
                    //if (isPreviewing)
                    //{
                    //    await mediaCapture.StopPreviewAsync();
                    //    captureImage.Source = null;
                    //    playbackElement.Source = null;
                    //    isPreviewing = false;
                    //}
                    //if (isRecording)
                    //{
                    //    await mediaCapture.StopRecordAsync();
                    //    isRecording = false;
                    //    recordVideo.Content = "Start Video Record";
                    //    recordAudio.Content = "Start Audio Record";
                    //}
                    mediaCapture.Dispose();
                    mediaCapture = null;
                }

                statusLabel.Text = "Initializing camera to capture audio and video...";
                // Use default initialization
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

                // Set callbacks for failure and recording limit exceeded
                statusLabel.Text = "Device successfully initialized for video recording!";
                //mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
                //mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);

                // Start Preview
                previewElement.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();

                //isPreviewing = true;
                statusLabel.Text = "Camera preview succeeded";

                // Enable buttons for video and photo capture
                //SetVideoButtonVisibility(Action.ENABLE);

                // Enable Audio Only Init button, leave the video init button disabled
                //audio_init.IsEnabled = true;
            }
            catch (Exception ex)
            {
                statusLabel.Text = "Unable to initialize camera for audio/video mode: \n" + ex.Message;
            }
        }
Exemplo n.º 10
0
        public async Task Start()
        {
            if (IsInitialized)
            {
                if (!IsPreviewActive)
                {
                    await MediaCapture.StartPreviewAsync();

                    IsPreviewActive = true;
                }
            }
        }
Exemplo n.º 11
0
        public async Task StartPreview()
        {
            Debug.WriteLine("Start Preview");
            await capture.StartPreviewAsync();

            isPreview = true;

            if (timer == null)
            {
                timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(CurrentVideoFrame), TimeSpan.FromMilliseconds(66));
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Asynchronously begins live webcam feed
 /// </summary>
 /// <returns>
 /// Task object.
 /// </returns>
 public async Task StartCameraPreview()
 {
     try
     {
         await mediaCapture.StartPreviewAsync();
     }
     catch
     {
         Debug.WriteLine("UsbCamera: Failed to start camera preview stream");
         throw;
     }
 }
Exemplo n.º 13
0
        private async Task StartPreviewAsync()
        {
            PreviewControl.Source = _mediaCapture;
            PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

            if (_mediaCapture != null)
            {
                await _mediaCapture.StartPreviewAsync();
                await SetPreviewRotationAsync();
                _isPreviewing = true;
            }
        }
Exemplo n.º 14
0
        private async Task InitPreview()
        {
            //Video and Audio is initialized by default
            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            // Start Preview
            PreviewElement.Source = mediaCapture;
            await mediaCapture.StartPreviewAsync();

            _lastTake = DateTime.Now.AddSeconds(0);
        }
        public async Task StartStreamAsync(bool isForRealTimeProcessing = false)
        {
            try
            {
                if (captureManager == null ||
                    captureManager.CameraStreamState == CameraStreamState.Shutdown ||
                    captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (captureManager != null)
                    {
                        captureManager.Dispose();
                    }

                    captureManager = new MediaCapture();

                    MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
                    var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    await captureManager.InitializeAsync(settings);
                    await SetVideoEncodingToHighestResolution(isForRealTimeProcessing);

                    this.webCamCaptureElement.Source = captureManager;
                }

                if (captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (this.faceTracker == null)
                    {
                        this.faceTracker = await FaceTracker.CreateAsync();
                    }

                    this.videoProperties = this.captureManager.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

                    await captureManager.StartPreviewAsync();

                    if (this.frameProcessingTimer != null)
                    {
                        this.frameProcessingTimer.Cancel();
                        frameProcessingSemaphore.Release();
                    }
                    TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); //15fps
                    this.frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);

                    this.cameraControlSymbol.Symbol      = Symbol.Camera;
                    this.webCamCaptureElement.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                await CoreUtil.GenericApiCallExceptionHandler(ex, "Lỗi khởi động camera.");
            }
        }
Exemplo n.º 16
0
        private async void InitializeMediaCapture()
        {
            try
            {
                DeviceInformationCollection devices = null;
                captureMgr = new MediaCapture();
                devices    = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


                // Use the front camera if found one
                if (devices == null || devices.Count == 0)
                {
                    isCameraFound = false;
                    return;
                }

                info = devices[0];

                MediaCaptureInitializationSettings settings;
                settings = new MediaCaptureInitializationSettings {
                    VideoDeviceId = info.Id
                };                                                                             // 0 => front, 1 => back

                await captureMgr.InitializeAsync(settings);

                VideoEncodingProperties resolutionMax = null;
                int max         = 0;
                var resolutions = captureMgr.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

                for (var i = 0; i < resolutions.Count; i++)
                {
                    VideoEncodingProperties res = (VideoEncodingProperties)resolutions[i];
                    if (res.Width * res.Height > max)
                    {
                        max           = (int)(res.Width * res.Height);
                        resolutionMax = res;
                    }
                }

                await captureMgr.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, resolutionMax);

                CaptureElement.Source = captureMgr;
                isCameraFound         = true;
                await captureMgr.StartPreviewAsync();
            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog("Error while initializing media capture device: " + ex.Message);
                dialog.ShowAsync();
                GC.Collect();
            }
        }
Exemplo n.º 17
0
        async void StartCapture()
        {
            // Disable all buttons until initialization completes
            BtnStart.IsEnabled = false;

            try
            {
                if (mediaCapture != null)
                {
                    // Cleanup MediaCapture object
                    if (isPreviewing)
                    {
                        await mediaCapture.StopPreviewAsync();

                        //captureImage.Source = null;
                        //playbackElement.Source = null;
                        isPreviewing = false;
                    }

                    mediaCapture.Dispose();
                    mediaCapture = null;
                }

                StatusBlock.Text = "Initializing camera to capture audio and video...";
                // Use default initialization
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

                // Set callbacks for failure and recording limit exceeded
                StatusBlock.Text     = "Device successfully initialized for video recording!";
                mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
                //mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);

                // Start Preview
                previewElement.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();

                isPreviewing     = true;
                StatusBlock.Text = "Camera preview succeeded";
                // Get information about the preview
                var previewProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

                // Create a video frame in the desired format for the preview frame
                videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);

                Configure();
            }
            catch (Exception ex)
            {
                StatusBlock.Text = "Unable to initialize camera for audio/video mode: " + ex.Message;
            }
        }
Exemplo n.º 18
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

            await _capture.InitializeAsync(new MediaCaptureInitializationSettings
            {
                VideoDeviceId        = await GetBackOrDefaulCameraIdAsync(),
                StreamingCaptureMode = StreamingCaptureMode.Video
            });

            IBuffer shaderY = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_Y.cso");

            IBuffer shaderUV = await PathIO.ReadBufferAsync("ms-appx:///Invert_093_NV12_UV.cso");

            var definition = new VideoEffects.ShaderEffectDefinitionNv12(shaderY, shaderUV);

            await _capture.AddEffectAsync(MediaStreamType.VideoRecord, definition.ActivatableClassId, definition.Properties);

            Preview.Source = _capture;
            await _capture.StartPreviewAsync();

            var previewProps = (VideoEncodingProperties)_capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            TextLog.Text += String.Format("Preview: {0} {1}x{2} {3}fps\n", previewProps.Subtype, previewProps.Width, previewProps.Height, previewProps.FrameRate.Numerator / (float)previewProps.FrameRate.Denominator);

            var recordProps = (VideoEncodingProperties)_capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord);

            TextLog.Text += String.Format("Record: {0} {1}x{2} {3}fps\n", recordProps.Subtype, recordProps.Width, recordProps.Height, recordProps.FrameRate.Numerator / (float)recordProps.FrameRate.Denominator);

            StorageFile file = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectRecordCaptureTestApp.mp4", CreationCollisionOption.ReplaceExisting);

            var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);

            profile.Audio = null;

            TextLog.Text += "Starting record\n";
            await _capture.StartRecordToStorageFileAsync(profile, file);

            TextLog.Text += "Record started to" + file.Path + "\n";

            for (int i = 0; i < 10; i++)
            {
                await Task.Delay(1000);

                TextLog.Text += i + "s\n";
            }

            TextLog.Text += "Stopping record\n";
            await _capture.StopRecordAsync();

            TextLog.Text += "Record stopped\n";
        }
Exemplo n.º 19
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //Загрузка настроек XMPP из файла настроек
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile   file          = await storageFolder.GetFileAsync("XMPP.cfg");

            using (var inputStream = await file.OpenReadAsync())
            {
                using (var classicStream = inputStream.AsStreamForRead())
                {
                    using (var streamReader = new StreamReader(classicStream))
                    {
                        string[] xmppConfig = new string[3];
                        int      i          = 0;

                        while (streamReader.Peek() >= 0)
                        {
                            xmppConfig[i] = streamReader.ReadLine();
                            i++;
                        }

                        xmppClient.SetXmppDomain(xmppConfig[0]);
                        xmppClient.SetUsername(xmppConfig[1]);
                        xmppClient.Password = xmppConfig[2];
                    }
                }
            }

            //Лицензия для библиотеки Matrix XMPP
            string lic = @"";

            Matrix.License.LicenseManager.SetLicense(lic);

            //Соединение с сервером XMPP
            xmppClient.Open();

            //Подготовка к захвату кадров
            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            //Получение списка режимов, в которых способна работать камера
            List <IMediaEncodingProperties> videoResolutions = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).ToList();
            await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview,
                                                                                   videoResolutions[3]);

            //Настройка вывода захваченных кадров
            previewElement.Source = mediaCapture;
            await mediaCapture.StartPreviewAsync();

            //Настройка обработчика кадров
            DispatcherTimerSetup();
        }
Exemplo n.º 20
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            DisplayRequest displayRequest = new DisplayRequest();

            try
            {
                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync();

                _mediaCapture.VideoDeviceController.DesiredOptimization = MediaCaptureOptimization.Quality;
                _mediaCapture.VideoDeviceController.PrimaryUse          = CaptureUse.Video;
                _mediaCapture.VideoDeviceController.TrySetPowerlineFrequency(PowerlineFrequency.SixtyHertz);

                try
                {
                    var comboBox = ComboBox;

                    var availableMediaStreamProperties = _mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord).ToList().OfType <VideoEncodingProperties>()
                                                         //.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate);
                                                         .ToList();

                    // Populate the combo box with the entries
                    foreach (VideoEncodingProperties property in availableMediaStreamProperties)
                    {
                        ComboBoxItem comboBoxItem = new ComboBoxItem();
                        comboBoxItem.Content = property.Width + "x" + property.Height + " " + property.FrameRate + "FPS " + property.Subtype;
                        comboBoxItem.Tag     = property;
                        comboBox.Items.Add(comboBoxItem);
                    }
                }
                catch (Exception)
                {
                }

                displayRequest.RequestActive();
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
            }
            catch (UnauthorizedAccessException)
            {
                // This will be thrown if the user denied access to the camera in privacy settings
                return;
            }

            try
            {
                PreviewControl.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();
            }
            catch (System.IO.FileLoadException)
            {
            }
        }
Exemplo n.º 21
0
        private async Task StartPreviewAsync()
        {
            try
            {
                m_mediaCapture = new MediaCapture();

                m_mediaCapture.Failed += OnMediaCaptureFailed;

                _displayRequest.RequestActive();

                // Populate orientation variables with the current state
                m_displayOrientation = m_displayInformation.CurrentOrientation;

                RegisterEventHandlers();

                m_mediaCapture.RecordLimitationExceeded += OnMediaCaptureRecordLimitationExceeded;

                var devInfo = await FindCameraDeviceByPanelAsync(m_desiredCameraPanel);

                var id = devInfo != null ? devInfo.Id : string.Empty;

                var settings = new MediaCaptureInitializationSettings();
                settings.VideoDeviceId = id;
                settings.MediaCategory = MediaCategory.Communications;

                await m_mediaCapture.InitializeAsync(settings);

                m_mediaCapture.SetEncoderProperty(MediaStreamType.VideoPreview, new Guid("9C27891A-ED7A-40e1-88E8-B22727A024EE"), PropertyValue.CreateUInt32(1));

                var resolutionMax = GetHighestResolution();

                ImageWidth  = resolutionMax.Width;
                ImageHeight = resolutionMax.Height;

                await m_mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, resolutionMax);

                m_PreviewVideoElement.Source = m_mediaCapture;
                await AddEffectsAsync();

                await m_mediaCapture.StartPreviewAsync();

                await SetPreviewRotationAsync();

                IsCaptureEnabled = true;

                UpdateButtonState();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 22
0
        private async Task StartPreviewAsync()
        {
            try
            {
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

                displayRequest.RequestActive();
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
            }
            catch (UnauthorizedAccessException)
            {
                // This will be thrown if the user denied access to the camera in privacy settings
                //ShowMessageToUser("The app was denied access to the camera");
                return;
            }

            try
            {
                previewControl = new CaptureElement()
                {
                    Source = mediaCapture
                };
                await mediaCapture.StartPreviewAsync();

                isPreviewing = true;
            }
            catch (System.IO.FileLoadException)
            {
                //mediaCapture.CaptureDeviceExclusiveControlStatusChanged += _mediaCapture_CaptureDeviceExclusiveControlStatusChanged;
                return;
            }

            figure = Figures.GetCube(new Point3D()
            {
                X = 0, Y = 0, Z = 100
            }, 70);

            await Task.Delay(TimeSpan.FromMilliseconds(100));

            canvLeft.Draw  += CanvasControlLeft_Draw;
            canvRight.Draw += CanvasControlRight_Draw;

            timer = new DispatcherTimer()
            {
                Interval = new TimeSpan(0, 0, 0, 0, 100)
            };
            timer.Tick += Timer_Tick;
            timer.Start();
            canvLeft.Visibility  = Visibility.Visible;
            canvRight.Visibility = Visibility.Visible;
        }
Exemplo n.º 23
0
        //BUTTONS & PROCEDURES

        private async void startCamera(object sender, RoutedEventArgs e)
        {
            if (isCapturing)
            {
                return;
            }
            isCapturing   = true;
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync();

            cePreview.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();
        }
Exemplo n.º 24
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            //Initialize media capture
            await mediaCapture.InitializeAsync();

            //Assign media capture to image control source
            PhotoPreview.Source = mediaCapture;

            //Start previewing
            await mediaCapture.StartPreviewAsync();

            base.OnNavigatedTo(e);
        }
Exemplo n.º 25
0
        ///<summary>
        ///    Activates capturing
        ///</summary>
        private async Task Camera()
        {
            if (isCapturing)
            {
                return;
            }
            isCapturing   = true;
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync();

            cePreview.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();
        }
Exemplo n.º 26
0
        private async Task CameraOn()
        {
            isCameraOn = true;
            _pi.SetLed(isCameraOn);

            //Video and Audio is initialized by default
            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            // Start Preview
            PreviewElement.Source = mediaCapture;
            await mediaCapture.StartPreviewAsync();
        }
Exemplo n.º 27
0
        private async Task <bool> InitMediaCapture()
        {
            _captureManager = new MediaCapture();
            await _captureManager.InitializeAsync();

            captureElement.Source        = _captureManager;
            captureElement.FlowDirection = FlowDirection.RightToLeft;

            // start capture preview
            await _captureManager.StartPreviewAsync();

            return(true);
        }
Exemplo n.º 28
0
        /// <inheritdoc />
        /// <summary>
        ///     カメラのプレビュー表示開始
        /// </summary>
        /// <returns></returns>
        public async Task StartPreview()
        {
            if (Initialized)
            {
                await MediaCapture.StartPreviewAsync();
            }
            else
            {
                await InitializeAsync();

                await MediaCapture.StartPreviewAsync();
            }
        }
Exemplo n.º 29
0
        private async Task StartVideoPreviewAsync()
        {
            await _mediaCapture.InitializeAsync();

            _displayRequest.RequestActive();
            PreviewControl.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); //15fps

            _frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);
            VideoProperties       = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
        }
Exemplo n.º 30
0
 /// <summary>
 /// Asynchronously begins live webcam feed
 /// </summary>
 public async Task StartCameraPreviewAsync()
 {
     try
     {
         CaptureElement.Source = MediaCapture;
         await MediaCapture.StartPreviewAsync();
     }
     catch
     {
         IsInitialized = false;
         Debug.WriteLine("Failed to start camera preview stream");
     }
 }