InitializeAsync() private method

private InitializeAsync ( ) : IAsyncAction
return IAsyncAction
Ejemplo n.º 1
0
        private async Task GetCapturePreview()
        {
            _capture = new MediaCapture();
            var Videodevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            //var rearCamera = Videodevices.FirstOrDefault(item => item.EnclosureLocation != null && item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
            var frontCamera = Videodevices.FirstOrDefault(item => item.EnclosureLocation != null && item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
            //TODO: カメラを切り替えられるようにする。



            try
            {
                await _capture.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = frontCamera.Id
                });
            }
            catch (Exception ex)
            {
                var message = new MessageDialog(ex.Message, "おや?なにかがおかしいようです。");
                await message.ShowAsync();
            }

            capturePreview.Source = _capture;

            await _capture.StartPreviewAsync();
        }
        //Record the Screen
        private async void btnRecord_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (btnRecord.IsChecked.HasValue && btnRecord.IsChecked.Value)
            {
                // Initialization - Set the current screen as input
                var scrCaptre = ScreenCapture.GetForCurrentView();              

                mCap = new MediaCapture();
                await mCap.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    VideoSource = scrCaptre.VideoSource,
                    AudioSource = scrCaptre.AudioSource,
                });

                // Start Recording to a File and set the Video Encoding Quality
                var file = await GetScreenRecVdo();
                await mCap.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), file);
            }
            else
            {
                // Stop recording and start playback of the file
                await StopRecording();

                //If Media Element is taken on XAML
                //var file = await GetScreenRecVdo(CreationCollisionOption.OpenIfExists);
                //OutPutScreen.SetSource(await file.OpenReadAsync(), file.ContentType);
            }
        }       
Ejemplo n.º 3
0
        private async Task intializeCamera()
        {
            if (captureManager == null)
            {
                captureManager = new MediaCapture();
                await captureManager.InitializeAsync();
            }

            capturePreview.Source = captureManager;
            await captureManager.StartPreviewAsync();

            try
            {
                play("This is add product page");
            }
            catch (System.IO.FileNotFoundException)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("Media player components unavailable");
                await messageDialog.ShowAsync();
            }
            catch (Exception)
            {
                media.AutoPlay = false;
                var messageDialog = new Windows.UI.Popups.MessageDialog("Unable to synthesize text");
                await messageDialog.ShowAsync();
            }
        }
Ejemplo n.º 4
0
        public async void Start(int camIndex)
        {
            // devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            if (devices.Count > 0)
            {
                // Using Windows.Media.Capture.MediaCapture APIs to stream from webcam
                mediaCaptureMgr = new MediaCapture();
                ///////////////////////////////////


                var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                captureInitSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Video;
                captureInitSettings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.VideoPreview;
                captureInitSettings.VideoDeviceId = devices[camIndex].Id;


                ///////////////////////////////////
                await mediaCaptureMgr.InitializeAsync(captureInitSettings);
                SetResolution();

                camCaptureElement.Source = mediaCaptureMgr;
                await mediaCaptureMgr.StartPreviewAsync();

            }
        }
Ejemplo n.º 5
0
        internal async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                btnStartDevice1.IsEnabled = false;
                ShowStatusMessage("Starting device");
                m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
                await m_mediaCaptureMgr.InitializeAsync();

                if (m_mediaCaptureMgr.MediaCaptureSettings.VideoDeviceId != "" && m_mediaCaptureMgr.MediaCaptureSettings.AudioDeviceId != "")
                {
                    btnStartPreview1.IsEnabled    = true;
                    btnStartStopRecord1.IsEnabled = true;
                    btnTakePhoto1.IsEnabled       = true;

                    ShowStatusMessage("Device initialized successful");

                    m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);
                    m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);
                }
                else
                {
                    btnStartDevice1.IsEnabled = true;
                    ShowStatusMessage("No VideoDevice/AudioDevice Found");
                }
            }
            catch (Exception exception)
            {
                ShowExceptionMessage(exception);
            }
        }
Ejemplo n.º 6
0
		/// <summary>
		/// Continuously look for a QR code
		/// NOTE: this method won't work if recording is enabled ('hey Cortana, start recording' thing).
		/// </summary>
		public static async Task<string> ReadAsync(CancellationToken token = default(CancellationToken))
		{
			var mediaCapture = new MediaCapture();
			await mediaCapture.InitializeAsync();
			await mediaCapture.AddVideoEffectAsync(new MrcVideoEffectDefinition(), MediaStreamType.Photo);

			var reader = new BarcodeReader();
			reader.Options.TryHarder = false;

			while (!token.IsCancellationRequested)
			{
				var imgFormat = ImageEncodingProperties.CreateJpeg();
				using (var ras = new InMemoryRandomAccessStream())
				{
					await mediaCapture.CapturePhotoToStreamAsync(imgFormat, ras);
					var decoder = await BitmapDecoder.CreateAsync(ras);
					using (var bmp = await decoder.GetSoftwareBitmapAsync())
					{
						Result result = await Task.Run(() =>
							{
								var source = new SoftwareBitmapLuminanceSource(bmp);
								return reader.Decode(source);
							});
						if (!string.IsNullOrEmpty(result?.Text))
							return result.Text;
					}
				}
				await Task.Delay(DelayBetweenScans);
			}
			return null;
		}
Ejemplo n.º 7
0
        private async void InitMediaCapture()
        {
            mediaCapture = null;
            mediaCapture = new Windows.Media.Capture.MediaCapture();

            // for dispose purpose
            (App.Current as App).MediaCapture   = mediaCapture;
            (App.Current as App).PreviewElement = capturePreview;

            await mediaCapture.InitializeAsync(captureInitSettings);

            // Add video stabilization effect during Live Capture
            //await _mediaCapture.AddEffectAsync(MediaStreamType.VideoRecord, Windows.Media.VideoEffects.VideoStabilization, null); //this will be deprecated soon
            Windows.Media.Effects.VideoEffectDefinition def = new Windows.Media.Effects.VideoEffectDefinition(Windows.Media.VideoEffects.VideoStabilization);
            await mediaCapture.AddVideoEffectAsync(def, MediaStreamType.VideoRecord);

            CreateProfile();

            // start preview

            capturePreview.Source = mediaCapture;

            DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;

            //// set the video Rotation
            //    _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            //    _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
        }
        // Click event handler for the "Start Device" button.
        private async void StartDevice_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StartDevice.IsEnabled = false;

                // Enumerate webcams.
                ShowStatusMessage("Enumerating webcams...");
                var devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                if (devInfoCollection.Count == 0)
                {
                    ShowStatusMessage("No webcams found");
                    return;
                }

                // Initialize the MediaCapture object, choosing the first found webcam.
                mediaCapture = new Windows.Media.Capture.MediaCapture();
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.VideoDeviceId = devInfoCollection[0].Id;
                await mediaCapture.InitializeAsync(settings);

                // We can now take photos and enable the grayscale effect.
                TakePhoto.IsEnabled = true;
                AddRemoveEffect.IsEnabled = true;

                ShowStatusMessage("Device initialized successfully");
            }
            catch (Exception ex)
            {
                ShowExceptionMessage(ex);
            }
        }
Ejemplo n.º 9
0
        private async Task InitializeCameraAsync()
        {
            if (mediaCapture == null)
            {
                // get camera device (back camera preferred)
                var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

                if (cameraDevice == null)
                {
                    Debug.WriteLine("no camera device found");
                    return;
                }

                // Create MediaCapture and its settings
                mediaCapture = new MediaCapture();

                var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

                // Initialize MediaCapture
                try
                {
                    await mediaCapture.InitializeAsync(settings);
                    isInitialized = true;
                }
                catch (UnauthorizedAccessException)
                {
                    Debug.WriteLine("access to the camera denied");
                }
            }
        }
        private async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                btnStartDevice4.IsEnabled = false;
                ShowStatusMessage("Starting device");
                m_capture = new Windows.Media.Capture.MediaCapture();

                await m_capture.InitializeAsync();

                if (m_capture.MediaCaptureSettings.VideoDeviceId != "")
                {
                    btnStartPreview4.IsEnabled = true;

                    ShowStatusMessage("Device initialized successful");

                    m_capture.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);
                }
                else
                {
                    btnStartDevice4.IsEnabled = true;
                    ShowStatusMessage("No Video Device Found");
                }
            }
            catch (Exception ex)
            {
                btnStartPreview4.IsEnabled = false;
                btnStartDevice4.IsEnabled  = true;
                ShowExceptionMessage(ex);
            }
        }
Ejemplo n.º 11
0
        public async Task InitializeAsync()
        {
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync();

            _imageEncodingProperties = ImageEncodingProperties.CreateJpeg();
        }
Ejemplo n.º 12
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            mediaCapture = new MediaCapture();
            DeviceInformationCollection devices =
        await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            // Use the front camera if found one
            if (devices == null) return;
            DeviceInformation info = devices[0];

            foreach (var devInfo in devices)
            {
                if (devInfo.Name.ToLowerInvariant().Contains("front"))
                {
                    info = devInfo;
                    frontCam = true;
                    continue;
                }
            }

            await mediaCapture.InitializeAsync(
                new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = info.Id
                });

            captureElement.Source = mediaCapture;
            captureElement.FlowDirection = frontCam ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
            await mediaCapture.StartPreviewAsync();

            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();
            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;

            DisplayInfo_OrientationChanged(displayInfo, null);
        }
Ejemplo n.º 13
0
		protected override async void Start()
		{
			ResourceCache.AutoReloadResources = true;
			base.Start();

			EnableGestureTapped = true;

			busyIndicatorNode = Scene.CreateChild();
			busyIndicatorNode.SetScale(0.06f);
			busyIndicatorNode.CreateComponent<BusyIndicator>();

			mediaCapture = new MediaCapture();
			await mediaCapture.InitializeAsync();
			await mediaCapture.AddVideoEffectAsync(new MrcVideoEffectDefinition(), MediaStreamType.Photo);
			await RegisterCortanaCommands(new Dictionary<string, Action> {
					{"Describe", () => CaptureAndShowResult(false)},
					{"Read this text", () => CaptureAndShowResult(true)}, 
					{"Enable preview", () => EnablePreview(true) },
					{"Disable preview", () => EnablePreview(false) },
					{"Help", Help }
				});
			
			ShowBusyIndicator(true);
			await TextToSpeech("Welcome to the Microsoft Cognitive Services sample for HoloLens and UrhoSharp.");
			ShowBusyIndicator(false);

			inited = true;
		}
        private async void This_Loaded( object sender, RoutedEventArgs e )
        {
            try
            {
                _camera = new MediaCapture();
                await _camera.InitializeAsync( new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = ( await GetBackCameraAsync() ).Id,
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    PhotoCaptureSource = PhotoCaptureSource.VideoPreview
                } );
                _camera.VideoDeviceController.FlashControl.Enabled = false;
                _camera.SetPreviewRotation( VideoRotation.Clockwise90Degrees );
                _camera.SetRecordRotation( VideoRotation.Clockwise90Degrees );

                CameraPreview.Source = _camera;
                await _camera.StartPreviewAsync();

                StartScanning();
            }
            catch
            {
                ErrorMessage.Visibility = Visibility.Visible;
            }
        }
Ejemplo n.º 15
0
        private async void InitCamera_Click(object sender, RoutedEventArgs e)
        {
            captureManager = new MediaCapture();
            await captureManager.InitializeAsync();

            // Can only read capabilities after capture device initialized.

            VideoDeviceController videoDeviceController = captureManager.VideoDeviceController;

            SceneModeControl sceneModeControl = _scene = videoDeviceController.SceneModeControl;
            RegionsOfInterestControl regionsOfInterestControl = _regions = videoDeviceController.RegionsOfInterestControl;

            bool isFocusSupported = _focus = videoDeviceController.FocusControl.Supported;
            bool isIsoSpeedSupported = _iso = videoDeviceController.IsoSpeedControl.Supported;
            bool isTorchControlSupported = _torch = videoDeviceController.TorchControl.Supported;
            bool isFlashControlSupported = _flash = videoDeviceController.FlashControl.Supported;

            if (_scene != null)
            {
                foreach (CaptureSceneMode mode in _scene.SupportedModes)
                {
                    string t = mode.ToString();
                }
            }

            if (_regions != null)
            {
                bool autoExposureSupported = _regions.AutoExposureSupported;
                bool autoFocusSupported = _regions.AutoFocusSupported;
                bool autoWhiteBalanceSupported = _regions.AutoWhiteBalanceSupported;
                uint maxRegions = _regions.MaxRegions;
            }
        }
        public async Task InitializeAsync()
        {
            if (Source != null)
            {
                return;
            }

            var deviceInformation = await TryGetDeviceInformationFromPanel(CurrentPanel);
            if (deviceInformation == null)
            {
                return;
            }

            Source = new MediaCapture();

            try
            {
                await
                    Source.InitializeAsync(new MediaCaptureInitializationSettings {VideoDeviceId = deviceInformation.Id});
                initialized = true;
            }
            catch
            {
                return;
            }

            var properties = Source.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
            configuration.UpdateSupportedVideoSizes(properties);
        }
Ejemplo n.º 17
0
        private async Task StartCamera()
        {
            var source = new Windows.Media.Capture.MediaCapture();

            try
            {
                //Use a specific camera
                var cameraId = await FindRearFacingCamera();

                if (!string.IsNullOrEmpty(cameraId))
                {
                    var settings = new MediaCaptureInitializationSettings();
                    settings.VideoDeviceId        = cameraId;
                    settings.StreamingCaptureMode = StreamingCaptureMode.Video;

                    await source.InitializeAsync(settings);

                    PreviewScreen.Source = source;

                    //Start video preview
                    await source.StartPreviewAsync();
                }
            }
            catch
            {
            }
        }
 private async void Page_Loaded(object sender, RoutedEventArgs e)
 {
     MediaCaptureInitializationSettings set = new MediaCaptureInitializationSettings();
     set.StreamingCaptureMode = StreamingCaptureMode.Video;
     mediaCapture = new MediaCapture();
     await mediaCapture.InitializeAsync(set);
 }
Ejemplo n.º 19
0
 public async Task StartPreviewAsync(VideoRotation videoRotation)
 {
     try
     {
         if (mediaCapture == null)
         {
             var cameraDevice = await FindCameraDeviceByPanelAsync(Panel.Back);
             mediaCapture = new MediaCapture();
             var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
             await mediaCapture.InitializeAsync(settings);
             captureElement.Source = mediaCapture;
             await mediaCapture.StartPreviewAsync();
             isPreviewing = true;
             mediaCapture.SetPreviewRotation(videoRotation);
             displayRequest.RequestActive();
         }
         //DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
     }
     catch (UnauthorizedAccessException)
     {
         // This will be thrown if the user denied access to the camera in privacy settings
         Debug.WriteLine("The app was denied access to the camera");
     }
     catch (Exception ex)
     {
         Debug.WriteLine("MediaCapture initialization failed. {0}", ex.Message);
     }
 }
Ejemplo n.º 20
0
        internal async Task InitializeCameraAsync()
        {
            Debug.WriteLine("InitializeCameraAsync");

            if (_mediaCapture == null)
            {
                // Attempt to get the back camera if one is available, but use any camera device if not
                var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

                if (cameraDevice == null)
                {
                    Debug.WriteLine("No camera device found!");
                    return;
                }

                // Create MediaCapture and its settings
                _mediaCapture = new MediaCapture();

                // Register for a notification when something goes wrong
                _mediaCapture.Failed += MediaCapture_Failed;

                var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

                // Initialize MediaCapture
                try
                {
                    await _mediaCapture.InitializeAsync(settings);
                    _isInitialized = true;
                }
                catch (UnauthorizedAccessException)
                {
                    Debug.WriteLine("The app was denied access to the camera");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
                }

                // If initialization succeeded, start the preview
                if (_isInitialized)
                {
                    // Figure out where the camera is located
                    if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                    {
                        // No information on the location of the camera, assume it's an external camera, not integrated on the device
                        _externalCamera = true;
                    }
                    else
                    {
                        // Camera is fixed on the device
                        _externalCamera = false;

                        // Only mirror the preview if the camera is on the front panel
                        _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                    }

                    await StartPreviewAsync();
                }
            }
        }
Ejemplo n.º 21
0
 public async static Task<bool> RequestMicrophonePermission()
 {
     try
     {
         var settings = new MediaCaptureInitializationSettings
         {
             StreamingCaptureMode = StreamingCaptureMode.Audio,
             MediaCategory = MediaCategory.Speech,
         };
         var capture = new MediaCapture();
         await capture.InitializeAsync(settings);
     }
     catch (UnauthorizedAccessException)
     {
         return false;
     }
     catch (Exception ex)
     {
         if (ex.HResult == -1072845856)
         {
             // No Audio Capture devices are present on this system.
         }
         return false;
     }
     return true;
 }
Ejemplo n.º 22
0
        public static async Task<List<DeviceInfo>> enumerateCameras()
        {
            var deviceInfo = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);
            List<DeviceInfo> devices = new List<DeviceInfo>();
            for (int i = 0; i < deviceInfo.Count; i++)
            {
                DeviceInfo device = new DeviceInfo();
                device.deviceID = deviceInfo[i].Id;
                device.deviceInfo = deviceInfo[i];
                device.deviceName = deviceInfo[i].Name;

                try
                {
                    MediaCaptureInitializationSettings mediaSetting = new MediaCaptureInitializationSettings();
                    setCaptureSettings(out mediaSetting, device.deviceID);
                    MediaCapture mCapture = new MediaCapture();
                    await mCapture.InitializeAsync(mediaSetting);
                    device.resolutionList = updateResolution(mCapture);
                }
                catch
                {
                }

                devices.Add(device);
            }

            return devices;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// On desktop/tablet systems, users are prompted to give permission to use capture devices on a 
        /// per-app basis. Along with declaring the microphone DeviceCapability in the package manifest,
        /// this method tests the privacy setting for microphone access for this application.
        /// Note that this only checks the Settings->Privacy->Microphone setting, it does not handle
        /// the Cortana/Dictation privacy check, however (Under Settings->Privacy->Speech, Inking and Typing).
        /// 
        /// Developers should ideally perform a check like this every time their app gains focus, in order to 
        /// check if the user has changed the setting while the app was suspended or not in focus.
        /// </summary>
        /// <returns>true if the microphone can be accessed without any permissions problems.</returns>
        /// 
        public async static Task<bool> RequestMicrophoneCapture()
        {
            try
            {
                // Request access to the microphone only, to limit the number of capabilities we need
                // to request in the package manifest.
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
                settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
                settings.MediaCategory = MediaCategory.Speech;
                MediaCapture capture = new MediaCapture();
                await capture.InitializeAsync(settings);
            }
            catch (UnauthorizedAccessException)
            {   // The user has turned off access to the microphone. If this occurs, we should show an error, or disable
                // functionality within the app to ensure that further exceptions aren't generated when 
                // recognition is attempted.
                return false;
            }
            catch (Exception exception)
            {
                // This can be replicated by using remote desktop to a system, but not redirecting the microphone input.
                // Can also occur if using the virtual machine console tool to access a VM instead of using remote desktop.
                if (exception.HResult == NoCaptureDevicesHResult)
                {
                    return false;
                }
                else
                {
                    throw;
                }

            }
            return true;
        }
Ejemplo n.º 24
0
 async private void Start_Capture_Preview_Click(object sender, RoutedEventArgs e)
 {
     captureManager = new MediaCapture();        //Define MediaCapture object
     await captureManager.InitializeAsync();     //Initialize MediaCapture and 
     capturePreview.Source = captureManager;     //Start preiving on CaptureElement
     await captureManager.StartPreviewAsync();   //Start camera capturing 
 }
Ejemplo n.º 25
0
        private async Task openCameraPopup()
        {
            MediaCapture mediaCapture = new Windows.Media.Capture.MediaCapture();
            await mediaCapture.InitializeAsync();

            mediaCapture.Dispose();
        }
Ejemplo n.º 26
0
        // Click event handler for the "Start Device" button.
        private async void StartDevice_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StartDevice.IsEnabled = false;

                // Enumerate webcams.
                ShowStatusMessage("Enumerating webcams...");
                var devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                if (devInfoCollection.Count == 0)
                {
                    ShowStatusMessage("No webcams found");
                    return;
                }

                // Initialize the MediaCapture object, choosing the first found webcam.
                mediaCapture = new Windows.Media.Capture.MediaCapture();
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.VideoDeviceId = devInfoCollection[0].Id;
                await mediaCapture.InitializeAsync(settings);

                // We can now take photos and enable the grayscale effect.
                TakePhoto.IsEnabled       = true;
                AddRemoveEffect.IsEnabled = true;

                ShowStatusMessage("Device initialized successfully");
            }
            catch (Exception ex)
            {
                ShowExceptionMessage(ex);
            }
        }
Ejemplo n.º 27
0
 private async void Loaded(object sender, RoutedEventArgs e)
 {
     MediaCapture capMana = new MediaCapture();
     await capMana.InitializeAsync();
     Webcam_Logitech.Source = capMana;
     await capMana.StartPreviewAsync();
 }
Ejemplo n.º 28
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Status.Text = "Status: " + "App started";

            //compass
            var compass = Windows.Devices.Sensors.Compass.GetDefault();
            compass.ReportInterval = 10;
            //compass.ReadingChanged += compass_ReadingChanged;
            Status.Text = "Status: " + "Compass started";

            //geo
            var gloc = new Geolocator();
            gloc.GetGeopositionAsync();
            gloc.ReportInterval = 60000;
            gloc.PositionChanged += gloc_PositionChanged;
            Status.Text = "Status: " + "Geo started";

            //Accelerometer
            var aclom = Accelerometer.GetDefault();
            aclom.ReportInterval = 1;
            aclom.ReadingChanged += aclom_ReadingChanged;

            //foursquare
            await GetEstablishmentsfromWed();

            //camera
            var mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();
            CaptureElement.Source = mediaCapture;
            await mediaCapture.StartPreviewAsync();
            Status.Text = "Status: " + "Camera feed running";
        }
        private async void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            var camera = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)).FirstOrDefault();

            if (camera != null)
            {
                mediaCapture = new MediaCapture();
                var settings = new MediaCaptureInitializationSettings() { VideoDeviceId = camera.Id };
                await mediaCapture.InitializeAsync(settings);
                displayRequest.RequestActive();
                VideoPreview.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();

                memStream = new InMemoryRandomAccessStream();
                MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                await mediaCapture.StartRecordToStreamAsync(mediaEncodingProfile, memStream);
            }
            //video = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);
            //if (video!=null)
            //{
            //    MediaClip mediaClip = await MediaClip.CreateFromFileAsync(video);
            //    mediaComposition.Clips.Add(mediaClip);
            //    mediaStreamSource = mediaComposition.GeneratePreviewMediaStreamSource(600, 600);
            //    VideoPreview.SetMediaStreamSource(mediaStreamSource);
            //}
            //FFMPEGHelper.RTMPEncoder encoder = new FFMPEGHelper.RTMPEncoder();
            //encoder.Initialize("rtmp://youtube.co");
        }
Ejemplo n.º 30
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (_mediaCapture == null)
            {
                // Attempt to get te back camera if one is available, but use any camera device if not
                var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(
                    x => x.EnclosureLocation != null & x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

                var cameraDevice = desiredDevice ?? allVideoDevices.FirstOrDefault();

                if (cameraDevice == null)
                {
                    // TODO: Implement an error experience for camera-less devices
                    Debug.Write("No camera device found.");
                    return;
                }

                // Create MediaCapture and its setings
                _mediaCapture = new MediaCapture();
                var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

                // TODO: Implement an error experience for non-authorized case
                await _mediaCapture.InitializeAsync(settings);

                // Startin the preview
                PreviewControl.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();
            }
        }
Ejemplo n.º 31
0
    public override async void Initialize()
    {
        if (QRCodeWatcher.IsSupported())
        {
#if WINDOWS_UWP
            try
            {
                var capture = new Windows.Media.Capture.MediaCapture();
                await capture.InitializeAsync();

                Debug.Log("Camera and Microphone permissions OK");
            }
            catch (UnauthorizedAccessException)
            {
                Debug.LogError("Camera and microphone permissions not granted.");
                return;
            }
#endif

            if (await QRCodeWatcher.RequestAccessAsync() == QRCodeWatcherAccessStatus.Allowed)
            {
                _qrWatcher          = new QRCodeWatcher();;
                _qrWatcher.Added   += OnQRCodeAddedEvent;
                _qrWatcher.Updated += OnQRCodeUpdatedEvent;
                _qrWatcher.Removed += OnQRCodeRemovedEvent;
                _qrWatcher.EnumerationCompleted += OnQREnumerationEnded;
            }
        }
    }
        /// <summary>
        /// This is the click handler for the 'StartPreview' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void StartPreview_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Check if the machine has a webcam
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                if (devices.Count > 0)
                {
                    rootPage.NotifyUser("", NotifyType.ErrorMessage);

                    if (mediaCaptureMgr == null)
                    {
                        // Using Windows.Media.Capture.MediaCapture APIs to stream from webcam
                        mediaCaptureMgr = new MediaCapture();
                        await mediaCaptureMgr.InitializeAsync();

                        VideoStream.Source = mediaCaptureMgr;
                        await mediaCaptureMgr.StartPreviewAsync();
                        previewStarted = true;

                        ShowSettings.Visibility = Visibility.Visible;
                        StartPreview.IsEnabled = false;
                    }
                }
                else
                {
                    rootPage.NotifyUser("A webcam is required to run this sample.", NotifyType.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                mediaCaptureMgr = null;
                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 33
0
        private async Task Initialize()
        {
            captureManager = new MediaCapture();

            await captureManager.InitializeAsync();
            capturePreview.Source = captureManager;
            await captureManager.StartPreviewAsync();
        }
Ejemplo n.º 34
0
        private async Task InitMediaCapture()
        {
            audioCapture = null;
            audioCapture = new Windows.Media.Capture.MediaCapture();

            // for dispose purpose
            (App.Current as App).MediaCapture = audioCapture;
            await audioCapture.InitializeAsync(captureInitSettings);
        }
Ejemplo n.º 35
0
 private async Task InitMediaCapture()
 {
     CaptureMedia = new MediaCapture();
     var captureInitSettings = new MediaCaptureInitializationSettings();
     captureInitSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;
     await CaptureMedia.InitializeAsync(captureInitSettings);
     CaptureMedia.Failed += MediaCaptureOnFailed;
     CaptureMedia.RecordLimitationExceeded += MediaCaptureOnRecordLimitationExceeded;
 }
Ejemplo n.º 36
0
        async private void IniciaPreviaCapturaFoto(object sender, RoutedEventArgs e)
        {
            GerenteCaptura = new Windows.Media.Capture.MediaCapture();
            await GerenteCaptura.InitializeAsync();

            GerenteCaptura.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            CapturaPrevia.Source = GerenteCaptura;
            await GerenteCaptura.StartPreviewAsync();
        }
Ejemplo n.º 37
0
        private async void InitializeAudioRecording()//初始化
        {
            _mediaCaptureManager = new MediaCapture();
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;//设置为音频
            settings.MediaCategory = MediaCategory.Other;//设置音频种类
            await _mediaCaptureManager.InitializeAsync(settings);

        }
Ejemplo n.º 38
0
        public async Task Init()
        {
            //TEST
            {
                bool isMicAvailable = true;
                try
                {
                    //var audioDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.AudioCapture);
                    //var audioId = audioDevices.ElementAt(0);

                    var mediaCapture = new Windows.Media.Capture.MediaCapture();
                    var settings     = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                    settings.StreamingCaptureMode =
                        Windows.Media.Capture.StreamingCaptureMode.Audio;
                    settings.MediaCategory = Windows.Media.Capture.MediaCategory.Communications;

                    //var _capture = new Windows.Media.Capture.MediaCapture();
                    //var _stream = new InMemoryRandomAccessStream();
                    //await _capture.InitializeAsync(settings);
                    //await _capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium), _stream);


                    await mediaCapture.InitializeAsync(settings);
                }
                catch (Exception)
                {
                    isMicAvailable = false;
                }
                if (!isMicAvailable)
                {
                    await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-microphone"));
                }
                else
                {
                }
            }
            // セットアップ
            {
                var language = new Windows.Globalization.Language("en-US");
                recognizer_ = new SpeechRecognizer(language);

                //this.dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

                recognizer_.ContinuousRecognitionSession.ResultGenerated +=
                    ContinuousRecognitionSession_ResultGenerated;

                recognizer_.ContinuousRecognitionSession.Completed +=
                    ContinuousRecognitionSession_Completed;

                recognizer_.HypothesisGenerated +=
                    SpeechRecognizer_HypothesisGenerated;

                SpeechRecognitionCompilationResult result = await recognizer_.CompileConstraintsAsync();

                System.Diagnostics.Debug.WriteLine(" compile res:" + result.Status.ToString());
            }
        }
Ejemplo n.º 39
0
        public async Task InitializeAsync()
        {
            // 録音をおこなうためのオブジェクトを生成する
            mediaCapture = new MediaCapture();

            // 録音用の初期化を開始する
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
            await mediaCapture.InitializeAsync(settings);
        }
Ejemplo n.º 40
0
		async void MainPage_Loaded(object sender, RoutedEventArgs e)
		{
			mediaCapture = new MediaCapture();
			await mediaCapture.InitializeAsync();

			CaptureElement.Source = mediaCapture;
			await mediaCapture.StartPreviewAsync();
			urhoApp = UrhoSurface.Run<UrhoApp>();
			urhoApp.CaptureVideo(CaptureFrameAsync);
		}
Ejemplo n.º 41
0
        async void InitCapture()
        {
            captureMgr = new Windows.Media.Capture.MediaCapture();

            await captureMgr.InitializeAsync();

            capturePreview.Source = captureMgr;

            await captureMgr.StartPreviewAsync();
        }
Ejemplo n.º 42
0
        async void RecordAndRotate(MediaCapture captureMgr)
        {
            captureMgr = new MediaCapture();
            await captureMgr.InitializeAsync();

            // <SnippetCaptureRotateSetRecordRotate>
            //captureMgr.SetRecordRotation(VideoRotation.Clockwise90Degrees);
            // </SnippetCaptureRotateSetRecordRotate>

            capturePreview.Source = captureMgr;
            await captureMgr.StartPreviewAsync();
        }
Ejemplo n.º 43
0
        // </SnippetMediaCaptureVideo_CreateProfileCS>

        // <SnippetMediaCaptureVideo_InitMCobjectCS>
        // Create and initialze the MediaCapture object.
        public async void InitMediaCapture()
        {
            _mediaCapture = null;
            // <SnippetMediaCaptureVideo_CreateMCobjectCS>
            _mediaCapture = new Windows.Media.Capture.MediaCapture();

            // Set the MediaCapture to a variable in App.xaml.cs to handle suspension.
            (App.Current as App).MediaCapture = _mediaCapture;
            // </SnippetMediaCaptureVideo_CreateMCobjectCS>

            await _mediaCapture.InitializeAsync(_captureInitSettings);

            CreateProfile();
        }
Ejemplo n.º 44
0
        private async void startAudioCapture()
        {
            m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
            var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

            settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
            settings.MediaCategory        = Windows.Media.Capture.MediaCategory.Other;
            settings.AudioProcessing      = (m_bRawAudioSupported && m_bUserRequestedRaw) ? Windows.Media.AudioProcessing.Raw : Windows.Media.AudioProcessing.Default;
            await m_mediaCaptureMgr.InitializeAsync(settings);

            EnableButton(true, "StartPreview");
            EnableButton(true, "StartStopRecord");
            EnableButton(true, "TakePhoto");
            ShowStatusMessage("Device initialized successfully");
            m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);;
            m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);;
        }
Ejemplo n.º 45
0
        public async void startPreview()
        {
            _mediaCapture = new Windows.Media.Capture.MediaCapture();
            (App.Current as App).MediaCapture = _mediaCapture;

            await _mediaCapture.InitializeAsync();

            CreateProfile();

            TurnMirroringOn();

            // <SnippetMediaCaptureVideo_StartPreview>
            // Start Previewing
            await _mediaCapture.StartPreviewAsync();

            (App.Current as App).IsPreviewing = true;
            // </SnippetMediaCaptureVideo_StartPreview>
        }
        internal async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                EnableButton(false, "StartDevice");
                ShowStatusMessage("Starting device");
                m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
                var settings      = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                var chosenDevInfo = m_devInfoCollection[EnumedDeviceList2.SelectedIndex];
                settings.VideoDeviceId = chosenDevInfo.Id;

                if (chosenDevInfo.EnclosureLocation != null && chosenDevInfo.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back)
                {
                    m_bRotateVideoOnOrientationChange = true;
                    m_bReversePreviewRotation         = false;
                }
                else if (chosenDevInfo.EnclosureLocation != null && chosenDevInfo.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front)
                {
                    m_bRotateVideoOnOrientationChange = true;
                    m_bReversePreviewRotation         = true;
                }
                else
                {
                    m_bRotateVideoOnOrientationChange = false;
                }

                await m_mediaCaptureMgr.InitializeAsync(settings);

                DisplayProperties_OrientationChanged(null);

                EnableButton(true, "StartPreview");
                EnableButton(true, "StartStopRecord");
                EnableButton(true, "TakePhoto");
                ShowStatusMessage("Device initialized successful");
                chkAddRemoveEffect.IsEnabled = true;
                m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);;
                m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);;
            }
            catch (Exception exception)
            {
                ShowExceptionMessage(exception);
            }
        }
Ejemplo n.º 47
0
        private async Task <MediaCapture> ConnectToCamera(int i, CaptureElement preview)
        {
            var manager = new Windows.Media.Capture.MediaCapture();

            var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (allVideoDevices.Count > i)
            {
                var cameraDevice = allVideoDevices[i];

                await manager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id, StreamingCaptureMode = StreamingCaptureMode.Video });

                var cameraProperties = manager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Select(x => x as VideoEncodingProperties).ToList();
                foreach (var mediaEncodingProperty in cameraProperties)
                {
                    Debug.WriteLine(mediaEncodingProperty.Width + "x" + mediaEncodingProperty.Height + " FPS: " + mediaEncodingProperty.FrameRate.Numerator + "Type:" + mediaEncodingProperty.Type + "   SubType:" + mediaEncodingProperty.Subtype);
                }


                foreach (var mediaEncodingProperty in cameraProperties)
                {
                    if (//mediaEncodingProperty.Width == 960 &&
                        //mediaEncodingProperty.Height == 544 &&
                        mediaEncodingProperty.Width == 320 &&
                        mediaEncodingProperty.Height == 240 &&
                        mediaEncodingProperty.FrameRate.Numerator == 15 &&
                        string.Compare(mediaEncodingProperty.Subtype, "YUY2") == 0)
                    {
                        Debug.WriteLine("Chosen: " + mediaEncodingProperty.Width + "x" + mediaEncodingProperty.Height + " FPS: " + mediaEncodingProperty.FrameRate.Numerator + "Type:" + mediaEncodingProperty.Type + "   SubType:" + mediaEncodingProperty.Subtype);
                        await manager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, mediaEncodingProperty);

                        break;
                    }
                }

                preview.Source = manager;
                await manager.StartPreviewAsync();
            }

            return(manager);
        }
        private async void CaptureImage(object parameter)
        {
            try
            {
                MediaCaptureManager = new Windows.Media.Capture.MediaCapture();
                await MediaCaptureManager.InitializeAsync();

                MediaCaptureManager.Failed += MediaCaptureManager_Failed;
                this._previewElement.Source = MediaCaptureManager;

                await MediaCaptureManager.StartPreviewAsync();

                this.PreviewEnabled = true;
                this.Idle           = true;
                SetupVideoPreviewSettings();
            }
            catch (Exception ex)
            {
                ShowFatalErrorMessageDialog(ex.Message, string.Empty);
            }
        }
Ejemplo n.º 49
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.visionService = new VisionService();
            var settings = new MediaCaptureInitializationSettings()
            {
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                VideoDeviceId        = "USB\\VID_046D&PID_C52B\\5&ECB7860&0&3",
                StreamingCaptureMode = StreamingCaptureMode.Video
            };

            captureManager = new MediaCapture();
            await captureManager.InitializeAsync();

            var timer = new DispatcherTimer()
            {
                Interval = TimeSpan.FromMilliseconds(50)
            };

            timer.Tick += Timer_Tick;

            timer.Start();
        }
        async public void initPhotoControl()
        {
            setMediaCaptureInitializationSettings();
            // reset all properties if photoManager contains an object.
            if (_captureManager != null)
            {
                _captureManager.Dispose();
                _captureManager = null;
            }
            _captureManager = new MediaCapture();
            await _captureManager.InitializeAsync(getMediaCaptureInitializationSettings());

            cptElementShowPreview.Source = _captureManager;

            await _captureManager.StartPreviewAsync();

            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();

            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;

            DisplayInfo_OrientationChanged(displayInfo, null);
        }
Ejemplo n.º 51
0
        internal async void btnStartDevice_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                EnableButton(false, "StartDevice");
                ShowStatusMessage("Starting device");
                m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
                await m_mediaCaptureMgr.InitializeAsync();

                EnableButton(true, "StartPreview");
                EnableButton(true, "StartStopRecord");
                EnableButton(true, "TakePhoto");
                ShowStatusMessage("Device initialized successful");

                m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);;
                m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);;
            }
            catch (Exception exception)
            {
                ShowExceptionMessage(exception);
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Register for the interrupt that is triggered when the device sends an interrupt to us.
        ///
        /// All interrupts happen on HidDevice, so once we register the event, all interrupts (regardless of the HidInputReport) will
        /// raise the event. Read the comment above OnGeneralInterruptEvent for more information on how to distinguish input reports.
        ///
        /// The function also saves the event token so that we can unregister from the even later on.
        /// </summary>
        /// <param name="eventHandler">Event handler that will be called when the event is raised</param>
        private async void RegisterForInterruptEvent(TypedEventHandler <HidDevice, HidInputReportReceivedEventArgs> eventHandler)
        {
            if (interruptEventHandler == null)
            {
                // Save the interrupt handler so we can use it to unregister
                interruptEventHandler = eventHandler;


                DeviceList.Current.CurrentDevice.InputReportReceived += interruptEventHandler;

                UpdateRegisterEventButton();

                // Prepare for media captures

                CaptureMgr = new Windows.Media.Capture.MediaCapture();
                await CaptureMgr.InitializeAsync();

                CaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);;
                CaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);;

                rootPage.NotifyUser("Video capture enabled.", NotifyType.StatusMessage);
            }
        }
Ejemplo n.º 53
0
        private async void v_Button_Capture_Click(object sender, RoutedEventArgs e)
        {
            isCapturing = !isCapturing;

            if (isCapturing)
            {
                if (isFirst)
                {
                    captureManager = new MediaCapture();

                    await captureManager.InitializeAsync();

                    capturePreview.Source = captureManager;
                    await captureManager.StartPreviewAsync();

                    isFirst = false;
                }
                v_Image.Source = null;
            }
            else
            {
                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();

                var stream = new InMemoryRandomAccessStream();

                await captureManager.CapturePhotoToStreamAsync(imageProperties, stream);

                _bitmap = new WriteableBitmap(300, 300);
                stream.Seek(0);
                await _bitmap.SetSourceAsync(stream);

                //await captureManager.StopPreviewAsync();

                v_Image.Source = _bitmap;
            }
        }
Ejemplo n.º 54
0
        internal async void button1_Click(object sender, RoutedEventArgs e)
        {
            /* Way one to use camera -> Full screen mode*/
            /* CameraCapture(); */
            /* Way two CaptureElement and canvas */

            try
            {
                button1.IsEnabled = false;
                //ShowStatusMessage("Starting device");
                m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
                await m_mediaCaptureMgr.InitializeAsync();

                if (m_mediaCaptureMgr.MediaCaptureSettings.VideoDeviceId != "" && m_mediaCaptureMgr.MediaCaptureSettings.AudioDeviceId != "")
                {
                    canpreview   = true;
                    canrecord    = true;
                    cantakephoto = true;

                    //ShowStatusMessage("Device initialized successful");

                    m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordLimitationExceeded);
                    m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(Failed);
                }
                else
                {
                    button1.IsEnabled = true;
                    //ShowStatusMessage("No VideoDevice/AudioDevice Found");
                }
            }
            catch (Exception exception)
            {
                //ShowExceptionMessage(exception);
            }

            /* So far the code was for starting the device*/

            /* Now the code to preview the image */

            m_bPreviewing = false;
            try
            {
                //ShowStatusMessage("Starting preview");
                button1.IsEnabled = false;
                canpreview        = false;

                previewCanvas1.Visibility = Windows.UI.Xaml.Visibility.Visible;
                previewElement1.Source    = m_mediaCaptureMgr;
                await m_mediaCaptureMgr.StartPreviewAsync();

                if ((m_mediaCaptureMgr.VideoDeviceController.Brightness != null) && m_mediaCaptureMgr.VideoDeviceController.Brightness.Capabilities.Supported)
                {
                    SetupVideoDeviceControl(m_mediaCaptureMgr.VideoDeviceController.Brightness, sldBrightness);
                }
                if ((m_mediaCaptureMgr.VideoDeviceController.Contrast != null) && m_mediaCaptureMgr.VideoDeviceController.Contrast.Capabilities.Supported)
                {
                    SetupVideoDeviceControl(m_mediaCaptureMgr.VideoDeviceController.Contrast, sldContrast);
                }
                rect1.Visibility = Visibility.Visible;
                m_bPreviewing    = true;
                //ShowStatusMessage("Start preview successful");

                captureclr.IsEnabled = true;
            }
            catch (Exception exception)
            {
                m_bPreviewing          = false;
                previewElement1.Source = null;
                /* If attempt to get preview fails he can try again */
                button1.IsEnabled = true;
                canpreview        = true;
                //ShowExceptionMessage(exception);
            }
        }
Ejemplo n.º 55
0
 async private void InitCamera_Click(object sender, RoutedEventArgs e)
 {
     captureManager = new MediaCapture();
     await captureManager.InitializeAsync();
 }
Ejemplo n.º 56
0
        // </SnippetMediaCaptureLowLagPhotoCaptureCode>


        async private void InitalizeCamera(MediaCapture captureManager)
        {
            captureManager = new MediaCapture();
            await captureManager.InitializeAsync();
        }
Ejemplo n.º 57
0
        public async void DevController()
        {
            // <SnippetMediaCaptureVideo_GetDeviceControllerCS>
            // Create the media capture object.
            var mediaCapture = new Windows.Media.Capture.MediaCapture();
            await mediaCapture.InitializeAsync();

            // Retrieve a video device controller.
            var videoDeviceController = mediaCapture.VideoDeviceController;

            // Retrieve an audio device controller.
            var audioDeviceController = mediaCapture.AudioDeviceController;
            // </SnippetMediaCaptureVideo_GetDeviceControllerCS>

            // <SnippetMediaCaptureVideo_SetVideoDeviceControllerPropertiesCS>
            // Retrieve the brightness capabilites of the video camera
            var brightnessCapabilities = videoDeviceController.Brightness.Capabilities;

            //
            // Determine if the video camera supports adjustment of the brightness setting.
            //
            if (brightnessCapabilities.Supported)
            {
                double brightness = 0;

                //
                // Retrieve the current brightness value.
                //

                if (videoDeviceController.Brightness.TryGetValue(out brightness))
                {
                    //
                    // Get the minimum, maximum and step size for the brightness value.
                    //
                    double min  = brightnessCapabilities.Min;
                    double max  = brightnessCapabilities.Max;
                    double step = brightnessCapabilities.Step;

                    //
                    // Increase the brightness value by one step as long as the new value is less than or equal to the maximum.
                    //

                    if ((brightness + step) <= max)
                    {
                        if (videoDeviceController.Brightness.TrySetValue(brightness + step))
                        {
                            // The brightness was successfully increased by one step.
                        }
                        else
                        {
                            // The brightness value couldn't be increased.
                        }
                    }
                    else
                    {
                        // The brightness value is greater than the maximum.
                    }
                }
                else
                {
                    // The brightness value couldn't be retrieved.
                }
            }
            else
            {
                // Setting the brightness value is not supported on this camera.
            }

            // </SnippetMediaCaptureVideo_SetVideoDeviceControllerProperties>
            // <SnippetMediaCaptureVideo_SetAudioDeviceControllerProperties>
            // Mute the microphone.
            audioDeviceController.Muted = true;

            // Un-mute the microphone.
            audioDeviceController.Muted = false;

            // Get the current volume setting.
            var currentVolume = audioDeviceController.VolumePercent;

            // Increase the volume by 10 percent, if possible.
            if (currentVolume <= 90)
            {
                audioDeviceController.VolumePercent = (currentVolume + 10);
            }
            // </SnippetMediaCaptureVideo_SetAudioDeviceControllerPropertiesCS>
        }
Ejemplo n.º 58
0
        public async void StartPreview()
        {
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var deviceInfo = devices[0]; //grab first result
            DeviceInformation rearCamera = null;

            foreach (var device in devices)
            {
                if (device.Name.ToLowerInvariant().Contains("front"))
                {
                    DeviceInformation frontCamera;
                    deviceInfo = frontCamera = device;
                    var hasFrontCamera = true;
                }
                if (device.Name.ToLowerInvariant().Contains("back"))
                {
                    rearCamera = device;
                }
            }

            var mediaSettings = new MediaCaptureInitializationSettings
            {
                MediaCategory        = MediaCategory.Communications,
                StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo,
                VideoDeviceId        = rearCamera.Id
            };

            var mediaCaptureManager = new Windows.Media.Capture.MediaCapture();
            await mediaCaptureManager.InitializeAsync(mediaSettings);

            var previewSink = new Windows.Phone.Media.Capture.MediaCapturePreviewSink();

            // List of supported video preview formats to be used by the default preview format selector.
            var supportedVideoFormats = new List <string> {
                "nv12", "rgb32"
            };

            // Find the supported preview format
            var availableMediaStreamProperties =
                mediaCaptureManager.VideoDeviceController.GetAvailableMediaStreamProperties(
                    Windows.Media.Capture.MediaStreamType.VideoPreview)
                .OfType <Windows.Media.MediaProperties.VideoEncodingProperties>()
                .Where(p => p != null &&
                       !String.IsNullOrEmpty(p.Subtype) &&
                       supportedVideoFormats.Contains(p.Subtype.ToLower()))
                .ToList();
            var previewFormat = availableMediaStreamProperties.FirstOrDefault();

            foreach (var property in availableMediaStreamProperties)
            {
                if (previewFormat.Width < property.Width)
                {
                    previewFormat = property;
                }
            }
            //previewFormat.Width = 480;
            //previewFormat.Height = 480;
            // Start Preview stream
            await mediaCaptureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(Windows.Media.Capture.MediaStreamType.VideoPreview, previewFormat);

            await mediaCaptureManager.StartPreviewToCustomSinkAsync(new Windows.Media.MediaProperties.MediaEncodingProfile {
                Video = previewFormat
            }, previewSink);

            var viewfinderBrush = new VideoBrush {
                Stretch = Stretch.Uniform
            };

            // Set the source of the VideoBrush used for your preview
            Microsoft.Devices.CameraVideoBrushExtensions.SetSource(viewfinderBrush, previewSink);
            CameraPreview.Background = viewfinderBrush;


            mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
        }