/// <summary>
        /// Stops camera.
        /// </summary>
        public async void StopCameraAsync()
        {
            if (CameraState != CameraStates.Initialized || _mediaCapture == null)
            {
                Debug.WriteLine(DebugTag + "StopCameraAsync(): Camera is not initialised");
                return;
            }

            CameraState             = CameraStates.Stopping;
            CaptureButton.IsEnabled = false;

            try
            {
                Debug.WriteLine(DebugTag + "StopCameraAsync(): Stopping camera...");
                await _mediaCapture.StopPreviewAsync();

                _mediaCapture.Dispose();
                _mediaCapture = null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(DebugTag + "StopCameraAsync(): Failed to stop camera: " + ex.ToString());
            }

            CameraState = CameraStates.NotInitialized;
        }
Beispiel #2
0
        /// <summary>
        /// Safely stops webcam streaming (if running) and releases MediaCapture object.
        /// </summary>
        private async void ShutdownWebCam()
        {
            if (mediaCapture != null)
            {
                if (mediaCapture.CameraStreamState == CameraStreamState.Streaming)
                {
                    try
                    {
                        await mediaCapture.StopPreviewAsync();

                        // Allow the device screen to sleep now that the preview is stopped
                        displayRequest.RequestRelease();
                    }
                    catch
                    {
                        // Since we're going to destroy the MediaCapture object there's nothing to do here
                    }
                }

                mediaCapture.Failed -= MediaCapture_CameraStreamFailed;
                mediaCapture.Dispose();
                preview.Source = null;
                mediaCapture   = null;
            }
        }
Beispiel #3
0
        private async void InitCamera()
        {
            try
            {
                if (mediaCapture != null)
                {
                    // Cleanup MediaCapture object
                    if (isPreviewing)
                    {
                        await mediaCapture.StopPreviewAsync();

                        isPreviewing = false;
                    }

                    mediaCapture.Dispose();
                    mediaCapture = null;
                }


                // Use default initialization
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

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

                isPreviewing = true;
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #4
0
        public async Task TakeSnapshotAsync(bool save = false)
        {
            // Camera device streaming may shutdown.  Have to re-initalize if this happens
            // real application should handle this by registering for CameraStreamStateChange event -
            // one of many camera state changes to handle.  For an example, see...
            // https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/BasicFaceDetection/cs/Scenario2_DetectInWebcam.xaml.cs

            if (this._mediaCapture.CameraStreamState == Windows.Media.Devices.CameraStreamState.Shutdown)
            {
                _mediaCapture.Dispose();
                _mediaCapture = new MediaCapture();
                await InitializeCameraAsync();
            }
            var capturedPhoto = await _lowLagCapture.CaptureAsync();

            // Convert to format that allows display by XAML as source.
            this.LastImage = SoftwareBitmap.Convert(capturedPhoto.Frame.SoftwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);;

            var source = new SoftwareBitmapSource();
            await source.SetBitmapAsync(this.LastImage);

            this.LastImageSource = source;

            if (save)
            {
                await SaveSoftwareBitmapToFile(this.LastImage, "mypic");
            }
        }
Beispiel #5
0
        private async void StartButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (!IsStarted)
            {
                cancellationToken = new CancellationTokenSource();
                IsStarted         = true;
//                CreateMediaCapture();

                this.StartButton.Content = "Stop";
                try
                {
                    await PeriodicTask.Run(async() =>
                    {
                        await CreateMediaCapture();
                        await TakePhoto_Click(null, null);
                        mediaCapture.Dispose();
                    }, TimeSpan.FromMinutes(2), cancellationToken.Token);
                }
                catch (OperationCanceledException)
                {
                    mediaCapture.Dispose();
                    IsStarted = false;
                    this.StartButton.Content = "Start";
                }
            }
            else
            {
                mediaCapture.Dispose();
                cancellationToken.Cancel();
                IsStarted = false;
                this.StartButton.Content = "Start";
            }
        }
Beispiel #6
0
        /// <summary>
        /// 'Initialize Audio and Video' button action function
        /// Dispose existing MediaCapture object and set it up for audio and video
        /// Enable or disable appropriate buttons
        /// - DISABLE 'Initialize Audio and Video'
        /// - DISABLE 'Start Audio Record'
        /// - ENABLE 'Initialize Audio Only'
        /// - ENABLE 'Start Video Record'
        /// - ENABLE 'Take Photo'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void initVideo_Click(object sender, RoutedEventArgs e)
        {
            // Disable all buttons until initialization completes

            SetInitButtonVisibility(Action.DISABLE);
            SetVideoButtonVisibility(Action.DISABLE);
            SetAudioButtonVisibility(Action.DISABLE);

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

                        isPreviewing = false;
                    }
                    if (isRecording)
                    {
                        await mediaCapture.StopRecordAsync();

                        isRecording         = false;
                        recordVideo.Content = "Start Video Record";
                        recordAudio.Content = "Start Audio Record";
                    }
                    mediaCapture.Dispose();
                    mediaCapture = null;
                }

                status.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
                status.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;
                status.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)
            {
                status.Text = "Unable to initialize camera for audio/video mode: " + ex.Message;
                SetInitButtonVisibility(Action.ENABLE);
            }
        }
                public async Task StopAsync()
                {
                    try
                    {
                        if (m_lowLag != null)
                        {
                            await m_lowLag.StopAsync();

                            await m_lowLag.FinishAsync();
                        }
                        else
                        {
                            await m_mediaCapture.StopRecordAsync();
                        }

                        m_mediaCapture.Dispose();
                        m_mediaCapture = null;

                        if (m_opusSink is IDisposable disposable)
                        {
                            disposable.Dispose();
                            m_opusSink = null;
                        }
                    }
                    catch { }
                }
Beispiel #8
0
        private async void Cleanup()
        {
            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;
            }
            SetInitButtonVisibility(Action.ENABLE);
        }
Beispiel #9
0
        public async void StopAudioRecording()
        {
            if (bRecordAudio == false)
            {
                return;
            }

            //crash on this line //due to invaid random access stream

            if (mediaCapture == null)
            {
                if (parent != null)
                {
                    parent.StartWritingOutput("Error Writing Audio", 1);
                }

                return;
            }

            await mediaCapture.StopRecordAsync();

            await SaveAudioToFile();

            mediaCapture.Dispose();
            mediaCapture = null;
        }
Beispiel #10
0
        private async Task <bool> SetupRecordProcess()
        {
            if (buffer != null)
            {
                buffer.Dispose();
            }
            buffer = new InMemoryRandomAccessStream();

            if (capture != null)
            {
                capture.Dispose();
            }

            try
            {
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                capture = new MediaCapture();
                await capture.InitializeAsync(settings);

                capture.RecordLimitationExceeded += RecordLimitExceedEventHandler;
                capture.Failed += CaptureFailedEventHandler;
            }
            catch (Exception ex)
            {
                ThrowException(ex);
                return(false);
            }
            return(true);
        }
Beispiel #11
0
    /// <summary>
    /// Method to start capturing camera frames at desired resolution.
    /// </summary>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public async Task InitializeMediaFrameReaderAsync(uint width = 224, uint height = 224)
    {
        // Check state of media capture object
        if (_mediaCapture == null || _mediaCapture.CameraStreamState == CameraStreamState.Shutdown || _mediaCapture.CameraStreamState == CameraStreamState.NotStreaming)
        {
            if (_mediaCapture != null)
            {
                _mediaCapture.Dispose();
            }

            // Find right camera settings and prefer back camera
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
            var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            Debug.Log($"InitializeMediaFrameReaderAsync: allCameras: {allCameras}");

            var selectedCamera = allCameras.FirstOrDefault(c => c.EnclosureLocation?.Panel == Panel.Back) ?? allCameras.FirstOrDefault();
            Debug.Log($"InitializeMediaFrameReaderAsync: selectedCamera: {selectedCamera}");


            if (selectedCamera != null)
            {
                settings.VideoDeviceId = selectedCamera.Id;
                Debug.Log($"InitializeMediaFrameReaderAsync: settings.VideoDeviceId: {settings.VideoDeviceId}");
            }

            // Init capturer and Frame reader
            _mediaCapture = new MediaCapture();
            Debug.Log("InitializeMediaFrameReaderAsync: Successfully created media capture object.");

            await _mediaCapture.InitializeAsync(settings);

            Debug.Log("InitializeMediaFrameReaderAsync: Successfully initialized media capture object.");

            var frameSource = _mediaCapture.FrameSources.Where(source => source.Value.Info.SourceKind == MediaFrameSourceKind.Color).First();
            Debug.Log($"InitializeMediaFrameReaderAsync: frameSource: {frameSource}.");

            // Convert the pixel formats
            var subtype = MediaEncodingSubtypes.Bgra8;

            // The overloads of CreateFrameReaderAsync with the format arguments will actually make a copy in FrameArrived
            BitmapSize outputSize = new BitmapSize {
                Width = width, Height = height
            };
            _mediaFrameReader = await _mediaCapture.CreateFrameReaderAsync(frameSource.Value, subtype, outputSize);

            Debug.Log("InitializeMediaFrameReaderAsync: Successfully created media frame reader.");

            _mediaFrameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime;

            await _mediaFrameReader.StartAsync();

            Debug.Log("InitializeMediaFrameReaderAsync: Successfully started media frame reader.");

            IsCapturing = true;
        }
    }
Beispiel #12
0
        // </SnippetFrameArrived>

        private async Task Cleanup()
        {
            // <SnippetCleanup>
            await mediaFrameReader.StopAsync();

            mediaFrameReader.FrameArrived -= ColorFrameReader_FrameArrived;
            mediaCapture.Dispose();
            mediaCapture = null;
            // </SnippetCleanup>
        }
Beispiel #13
0
        /// <summary>
        /// 'Initialize Audio and Video' button action function
        /// Dispose existing MediaCapture object and set it up for audio and video
        /// Enable or disable appropriate buttons
        /// - DISABLE 'Initialize Audio and Video'
        /// - DISABLE 'Start Audio Record'
        /// - ENABLE 'Initialize Audio Only'
        /// - ENABLE 'Start Video Record'
        /// - ENABLE 'Take Photo'
        /// </summary>
        public async Task <string> InitializeCamera()
        {
            //TODO: Disable all buttons until initialization completes

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

                        isPreviewing = false;
                    }
                    if (isRecording)
                    {
                        await mediaCapture.StopRecordAsync();

                        isRecording = false;
                    }
                    mediaCapture.Dispose();
                    mediaCapture = null;
                }

                Debug.WriteLine("Initializing camera to capture audio and video...");

                // Use default initialization
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

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


                /*
                 * // Start Preview
                 * await mediaCapture.StartPreviewAsync();
                 * isPreviewing = true;
                 * string message = "{\"message\":\"Camera preview succeeded\"}";
                 * Debug.WriteLine(message);
                 */

                return(message);
            }
            catch (Exception ex)
            {
                string message = "Unable to initialize camera for audio/video mode: " + ex.Message;
                Debug.WriteLine(message);
                return(message);
            }
        }
Beispiel #14
0
        // webcameraのスタート
        private async Task StartWebCameraAsync()
        {
            try
            {
                if (_captureManager == null ||
                    _captureManager.CameraStreamState == CameraStreamState.Shutdown ||
                    _captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (_captureManager != null)
                    {
                        // captureManagerのリソースを解放する
                        _captureManager.Dispose();
                    }

                    // LifeCam優先で、それがなければ取得した全カメラIDのリストから先頭のものを使用する
                    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;
                    }

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

                    WebCamCaptureElement.Source = _captureManager;
                }

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

                    // 15fpsで動作
                    // 66milsecond毎にCreatePeriodicTimerの第一引き数に渡したHandlerで指定したメソッドが実行される
                    TimeSpan timeInterval = TimeSpan.FromMilliseconds(66);
                    _frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timeInterval);
                    _videoProperties      = _captureManager.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

                    await _captureManager.StartPreviewAsync();

                    WebCamCaptureElement.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                Debug.Write("6");
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}");
            }
        }
        /// <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}");
            }
        }
Beispiel #16
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;
            }
        }
Beispiel #17
0
 public override void Dispose()
 {
     Streaming = false;
     if (Reader != null)
     {
         Reader.FrameArrived -= NewFrameArrived;
         Reader.Dispose();
     }
     if (NativeDevice != null)
     {
         NativeDevice.Dispose();
     }
 }
Beispiel #18
0
        private async Task WatchFrames()
        {
            long count   = 0;
            long changes = 0;
            // TODO You may need to customize the line below for your camera.  If you do run in debug mode and all valid values for your camera will be output.
            VideoFrame    currentFrame = new VideoFrame(BitmapPixelFormat.Nv12, 352, 288);
            FrameAnalysis analysis     = new FrameAnalysis();

            while (_isSyncing)
            {
                try
                {
                    await _mediaCapture.GetPreviewFrameAsync(currentFrame);

                    analysis.AnalyzeFrame(ref currentFrame,
                                          Settings.TheAnalysisAlgorithm,
                                          Settings.TheBiasAlgorithm,
                                          (int)Settings.CalibreationTop,
                                          (int)Settings.CalibrationLeft,
                                          (int)(Settings.CalibreationTop + Settings.CalibrationHeight),
                                          (int)(Settings.CalibrationLeft + Settings.CalibrationWidth));
                    count++;

                    if (await _hue.ChangeFilteredLightsColor(analysis.Red, analysis.Green, analysis.Blue))
                    {
                        frequent.Fill = new SolidColorBrush(Color.FromArgb(255, analysis.Red, analysis.Green, analysis.Blue));
                        changes++;
                    }
                    if (_calState == CalibrationState.NotCalibrating)
                    {
                        fps.Text =
                            $"Frames: {count} Changes: {changes} Values:{analysis.Red},{analysis.Green},{analysis.Blue},{analysis.Alpha}";
                    }
                }
                catch (Exception ex)
                {
                    UpdateStatus(ex.Message);
                }
            }


            var stopPreviewTask   = _mediaCapture.StopPreviewAsync();
            var turnOffLightsTask = _hue.TurnOffFilteredLights();

            await stopPreviewTask;
            await turnOffLightsTask;

            _mediaCapture.Dispose();
            _mediaCapture = null;
            SetStartupButtonVisibility();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            if (isPreview)
            {
                await capture.StopPreviewAsync();
            }

            if (isRecording)
            {
                await capture.StopRecordAsync();
            }
            capture.Dispose();
            capture = null;
        }
Beispiel #20
0
        //放弃录音
        private void cancel_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (_mediaCaptureManager != null)
            {
                _mediaCaptureManager.Dispose();
                _mediaCaptureManager = null;
            }

            gridRecord.Visibility = Visibility.Collapsed;


            stop.Visibility   = Visibility.Visible;
            cancel.Visibility = Visibility.Collapsed;
            accept.Visibility = Visibility.Collapsed;
        }
Beispiel #21
0
        public async Task StopScanningAsync()
        {
            stopping    = true;
            isAnalyzing = false;

            try
            {
                await mediaCapture.StopPreviewAsync();

                if (UseCustomOverlay && CustomOverlay != null)
                {
                    gridCustomOverlay.Children.Remove(CustomOverlay);
                }
            }
            catch { }
            finally {
                //second execution from sample will crash if the object is not properly disposed (always on mobile, sometimes on desktop)
                mediaCapture.Dispose();
            }

            //this solves a crash occuring when the user rotates the screen after the QR scanning is closed
            displayInformation.OrientationChanged -= displayInformation_OrientationChanged;

            timerPreview.Change(Timeout.Infinite, Timeout.Infinite);
            stopping = false;
        }
Beispiel #22
0
        public async Task CleanupAsync()
        {
            Log("Viewport.CleanupAsync");

            if (mediaCapture != null)
            {
                if (isPreviewing)
                {
                    await mediaCapture.StopPreviewAsync();
                    Log("Viewport: MediaCapture.StopPreviewAsync");
                }

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    cameraPreview.Source = null;

                    mediaCapture.Dispose();
                    mediaCapture = null;
                    Log("Viewport: MediaCapture Disposed");

                    if (displayRequest != null)
                    {
                        displayRequest.RequestRelease();
                        Log("Viewport: DisplayRequest.RequestRelease");
                    }
                });
            }
        }
        /// <summary>
        /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
        /// </summary>
        /// <returns></returns>
        private async Task CleanupCameraAsync()
        {
            Debug.WriteLine("CleanupCameraAsync");

            if (_isInitialized)
            {
                if (_isPreviewing)
                {
                    // The call to stop the preview is included here for completeness, but can be
                    // safely removed if a call to MediaCapture.Dispose() is being made later,
                    // as the preview will be automatically stopped at that point
                    await StopPreviewAsync();
                }

                if (_advancedCapture != null)
                {
                    await DisableHdrAsync();
                }

                if (_sceneAnalysisEffect != null)
                {
                    await CleanSceneAnalysisEffectAsync();
                }

                _isInitialized = false;
            }

            if (_mediaCapture != null)
            {
                _mediaCapture.Failed -= MediaCapture_Failed;
                _mediaCapture.Dispose();
                _mediaCapture = null;
            }
        }
Beispiel #24
0
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //Dispose media capture when navigating away from this page
            mediaCapture.Dispose();

            base.OnNavigatedFrom(e);
        }
Beispiel #25
0
        public async Task <List <MediaFrameFormat> > GetMediaFrameFormatsAsync()
        {
            var mediaFrameFormats = new List <MediaFrameFormat>();

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAndAwaitAsync(CoreDispatcherPriority.Normal, async() =>
            {
                var mediaCapture = new MediaCapture();

                var settings = new MediaCaptureInitializationSettings()
                {
                    MemoryPreference     = MediaCaptureMemoryPreference.Cpu,
                    StreamingCaptureMode = StreamingCaptureMode.Video
                };

                await mediaCapture.InitializeAsync(settings);

                var mediaFrameSource = mediaCapture.FrameSources.First().Value;

                mediaFrameFormats = mediaFrameSource.SupportedFormats.ToList();

                mediaCapture.Dispose();
            });

            return(mediaFrameFormats);
        }
        /// <summary>
        /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
        /// </summary>
        /// <returns></returns>
        private async Task CleanupCameraAsync()
        {
            Debug.WriteLine("CleanupCameraAsync");

            if (_isInitialized)
            {
                // If a recording is in progress during cleanup, stop it to save the recording
                if (_isRecording)
                {
                    await StopRecordingAsync();
                }

                if (_isPreviewing)
                {
                    // The call to stop the preview is included here for completeness, but can be
                    // safely removed if a call to MediaCapture.Dispose() is being made later,
                    // as the preview will be automatically stopped at that point
                    await StopPreviewAsync();
                }

                _isInitialized = false;
            }

            if (_mediaCapture != null)
            {
                _mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded;
                _mediaCapture.Failed -= MediaCapture_Failed;
                _mediaCapture.Dispose();
                _mediaCapture = null;
            }
        }
Beispiel #27
0
        private async Task CleanupCameraAsync()
        {
            timer.Stop();

            do
            {
                lock (lockObj)
                {
                    if (methodCount <= 0)
                    {
                        break;
                    }
                }
                await Task.Delay(TimeSpan.FromMilliseconds(100));
            } while (true);

            if (mediaCapture != null)
            {
                if (isPreviewing)
                {
                    await mediaCapture.StopPreviewAsync();
                }

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    if (displayRequest != null)
                    {
                        displayRequest.RequestRelease();
                    }

                    mediaCapture.Dispose();
                    mediaCapture = null;
                });
            }
        }
        /// <summary>
        /// MediaCaptureインスタンスの作成
        /// </summary>
        /// <param name="frameSourceGroup"></param>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        private async Task <bool> CreateMediaCaptureAsync(MediaFrameSourceGroup frameSourceGroup, DeviceInformation deviceInfo)
        {
            if (_mediaCapture != null)
            {
                return(false);
            }

            _mediaCapture = new MediaCapture();
            // 設定オブジェクトの作成、MediaFrameSourceGroupを指定している
            // 取得した画像(フレーム)をバイナリで取得するため、
            // フレームをSoftwareBitmapとして取得できるようMemoryPreferenceを設定する
            var settings = new MediaCaptureInitializationSettings()
            {
                VideoDeviceId        = deviceInfo.Id,
                SourceGroup          = frameSourceGroup,
                MemoryPreference     = MediaCaptureMemoryPreference.Cpu,
                StreamingCaptureMode = StreamingCaptureMode.Video
            };

            // MediaCaptureの初期化
            try
            {
                await _mediaCapture.InitializeAsync(settings);

                _mediaCapture.VideoDeviceController.Focus.TrySetAuto(true);
                return(true);
            } catch (Exception)
            {
                // 何かしらの例外が発生
                _mediaCapture.Dispose();
                _mediaCapture = null;
                return(false);
            }
        }
Beispiel #29
0
        public async void Capture_Click(object sender, RoutedEventArgs e)
        {
            MediaCapture mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            if (mediaCapture.VideoDeviceController.LowLagPhotoSequence.Supported)
            {
                mediaCapture.Dispose();
                Frame.Navigate(typeof(SequenceCapturePage));
            }
            else
            {
                mediaCapture.Dispose();
                Frame.Navigate(typeof(VideoPreviewCapturePage));
            }
        }
Beispiel #30
0
        public async Task StopEverything()
        {
            if (Preview.Previewing)
            {
                await Preview.StopAsync();
            }

            if (Video.Capturing)
            {
                await Video.StopAsync();
            }

            if (FaceDetection != null)
            {
                FaceDetection.Enabled       = false;
                FaceDetection.FaceDetected -= FaceDetection_FaceDetected;
            }

            if (DefaultManager != null)
            {
                DefaultManager.RecordLimitationExceeded -= DefaultManager_RecordLimitationExceeded;
                await DefaultManager.ClearEffectsAsync(MediaStreamType.VideoPreview);

                DefaultManager.Dispose();
                DefaultManager = null;
            }
        }