Inheritance: IMediaCaptureInitializationSettings
        /// <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;
        }
 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);
     }
 }
        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");
        }
        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
            m_mediaCapture = new MediaCapture();
            m_mediaCapture.Failed += mediaCapture_Failed;

            var settings = new MediaCaptureInitializationSettings()
            {
                StreamingCaptureMode = StreamingCaptureMode.Video
            };

            try
            {
                await m_mediaCapture.InitializeAsync(settings);
                
                await m_mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, GetHighestResolution());
            }
            catch (Exception)
            {               
                return;
            }

            await m_mediaCapture.AddVideoEffectAsync( new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName, new PropertySet()), MediaStreamType.VideoPreview);

            m_previewVideoElement.Source = m_mediaCapture;
            await m_mediaCapture.StartPreviewAsync();
        }
Beispiel #5
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);
            }
        }
Beispiel #6
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;
        }
        // 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);
            }
        }
 private async void Page_Loaded(object sender, RoutedEventArgs e)
 {
     MediaCaptureInitializationSettings set = new MediaCaptureInitializationSettings();
     set.StreamingCaptureMode = StreamingCaptureMode.Video;
     mediaCapture = new MediaCapture();
     await mediaCapture.InitializeAsync(set);
 }
Beispiel #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");
                }
            }
        }
Beispiel #10
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();
            }
        }
 private MediaCaptureInitializationSettings GetSettings()
 {
     MediaCaptureInitializationSettings result = new MediaCaptureInitializationSettings();
     result.StreamingCaptureMode = StreamingCaptureMode.Audio;
     result.AudioProcessing = Windows.Media.AudioProcessing.Default;
     return result;
 }
        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();
                }
            }
        }
        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();

            }
        }
Beispiel #14
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;
 }
Beispiel #15
0
        public async void StartRecording()
        {
            try
            {
                var screenCapture = Windows.Media.Capture.ScreenCapture.GetForCurrentView();
                // Set the MediaCaptureInitializationSettings to use the ScreenCapture as the
                // audio and video source.
                var mcis = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                mcis.VideoSource          = screenCapture.VideoSource;
                mcis.AudioSource          = screenCapture.AudioSource;
                mcis.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
                // Initialize the MediaCapture with the initialization settings.
                this.screenRecord = new MediaCapture();
                await this.screenRecord.InitializeAsync(mcis);

                // Create a file to record to.
                StorageFile videoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("recording.mp4", CreationCollisionOption.ReplaceExisting);

                // Create an encoding profile to use.
                var profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto);
                // Start recording
                await this.screenRecord.StartRecordToStorageFileAsync(profile, videoFile);

                this.isRecoding = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Global.Current.Notifications.CreateToastNotifier("test", "Starterror");
            }
        }
        /// <summary>
        /// Locates a video profile for the back camera and then queries if
        /// the discovered profile supports 640x480 30 FPS recording.
        /// If a supported profile is located, then we configure media
        /// settings to the matching profile. Else we use default profile.
        /// </summary>
        /// <param name="sender">Contains information regarding button that fired event</param>
        /// <param name="e">Contains state information and event data associated with the event</param>
        private async void InitRecordProfileBtn_Click(object sender, RoutedEventArgs e)
        {
            MediaCapture mediaCapture = new MediaCapture();
            MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings();
            string videoDeviceId = string.Empty;

            // Look for a video capture device Id with a video profile matching panel location
            videoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Back);

            if (string.IsNullOrEmpty(videoDeviceId))
            {
                await LogStatus("ERROR: No Video Device Id found, verify your device supports profiles", NotifyType.ErrorMessage);
                return;
            }

            await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Found video capture device that supports Video Profile, Device Id:\r\n {0}", videoDeviceId));
            await LogStatusToOutputBox("Retrieving all Video Profiles");
            IReadOnlyList<MediaCaptureVideoProfile> profiles = MediaCapture.FindAllVideoProfiles(videoDeviceId);

            await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Number of Video Profiles found: {0}", profiles.Count));

            // Output all Video Profiles found, frame rate is rounded up for display purposes
            foreach (var profile in profiles)
            {
                var description = profile.SupportedRecordMediaDescription;
                foreach (var desc in description)
                {
                    await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture,
                        "Video Profile Found: Profile Id: {0}\r\n Width: {1} Height: {2} FrameRate: {3}", profile.Id, desc.Width, desc.Height, Math.Round(desc.FrameRate).ToString()));
                }
            }

            // Look for WVGA 30FPS profile 
            await LogStatusToOutputBox("Querying for matching WVGA 30FPS Profile");
            var match = (from profile in profiles
                         from desc in profile.SupportedRecordMediaDescription
                         where desc.Width == 640 && desc.Height == 480 && Math.Round(desc.FrameRate) == 30
                         select new { profile, desc }).FirstOrDefault();

            if (match != null)
            {
                mediaInitSettings.VideoProfile = match.profile;
                mediaInitSettings.RecordMediaDescription = match.desc;
                await LogStatus(string.Format(CultureInfo.InvariantCulture,
                        "Matching WVGA 30FPS Video Profile found: \r\n Profile Id: {0}\r\n Width: {1} Height: {2} FrameRate: {3}",
                        mediaInitSettings.VideoProfile.Id, mediaInitSettings.RecordMediaDescription.Width,
                        mediaInitSettings.RecordMediaDescription.Height, Math.Round(mediaInitSettings.RecordMediaDescription.FrameRate).ToString()), NotifyType.StatusMessage);
            }
            else
            {
                // Could not locate a WVGA 30FPS profile, use default video recording profile
                mediaInitSettings.VideoProfile = profiles[0];
                await LogStatus("Could not locate a matching profile, setting to default recording profile", NotifyType.ErrorMessage);
            }

            await mediaCapture.InitializeAsync(mediaInitSettings);
            await LogStatusToOutputBox("Media Capture settings initialized to selected profile");

        }
Beispiel #17
0
        private async void InitializeAudioRecording()//初始化
        {
            _mediaCaptureManager = new MediaCapture();
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;//设置为音频
            settings.MediaCategory = MediaCategory.Other;//设置音频种类
            await _mediaCaptureManager.InitializeAsync(settings);

        }
Beispiel #18
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;
 }
Beispiel #19
0
        /// <summary>
        /// 'Initialize Audio Only' button action function
        /// Dispose existing MediaCapture object and set it up for audio only
        /// Enable or disable appropriate buttons
        /// - DISABLE 'Initialize Audio Only'
        /// - DISABLE 'Start Video Record'
        /// - DISABLE 'Take Photo'
        /// - ENABLE 'Initialize Audio and Video'
        /// - ENABLE 'Start Audio Record'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void initAudioOnly_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();

                        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;
                }

                status.Text  = "Initializing camera to capture audio only...";
                mediaCapture = new MediaCapture();
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
                settings.MediaCategory        = Windows.Media.Capture.MediaCategory.Other;
                settings.AudioProcessing      = Windows.Media.AudioProcessing.Default;
                await mediaCapture.InitializeAsync(settings);

                // Set callbacks for failure and recording limit exceeded
                status.Text          = "Device successfully initialized for audio recording!" + "\nPress \'Start Audio Record\' to record";
                mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
                mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);

                // Enable buttons for audio
                SetAudioButtonVisibility(Action.ENABLE);

                // Enable Audio and video Only Init button
                video_init.IsEnabled = true;
            }
            catch (Exception ex)
            {
                status.Text = "Unable to initialize camera for audio mode: " + ex.Message;
                SetInitButtonVisibility(Action.ENABLE);
            }
        }
Beispiel #20
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());
            }
        }
        public async Task InitializeAsync()
        {
            // 録音をおこなうためのオブジェクトを生成する
            mediaCapture = new MediaCapture();

            // 録音用の初期化を開始する
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
            await mediaCapture.InitializeAsync(settings);
        }
Beispiel #22
0
 private async Task Init()
 {
     MC = new MediaCapture();
     var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
     var camera = cameras.First();
     var settings = new MediaCaptureInitializationSettings() { VideoDeviceId = camera.Id };
     await MC.InitializeAsync(settings);
     ViewFinder.Source = MC;
     await MC.StartPreviewAsync();
 }
 async void InitCamera()
 {
     mc = new MediaCapture();
     var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
     var camera = cameras[1];
     var settings = new MediaCaptureInitializationSettings() { VideoDeviceId = camera.Id };
     await mc.InitializeAsync(settings);
     ce.Source = mc;
     await mc.StartPreviewAsync();
 }
Beispiel #24
0
      protected override async void OnNavigatedTo(NavigationEventArgs e)
      {
         try
         {
            var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            if (cameras.Count < 1)
            {
               Error.Text = "No camera found, decoding static image";
               await DecodeStaticResource();
               return;
            }
            MediaCaptureInitializationSettings settings;
            if (cameras.Count == 1)
            {
               settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id }; // 0 => front, 1 => back
            }
            else
            {
               settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[1].Id }; // 0 => front, 1 => back
            }

            await _mediaCapture.InitializeAsync(settings);
            VideoCapture.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            while (_result == null)
            {
               var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName);
               await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);

               var stream = await photoStorageFile.OpenReadAsync();
               // initialize with 1,1 to get the current size of the image
               var writeableBmp = new WriteableBitmap(1, 1);
               writeableBmp.SetSource(stream);
               // and create it again because otherwise the WB isn't fully initialized and decoding
               // results in a IndexOutOfRange
               writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
               stream.Seek(0);
               writeableBmp.SetSource(stream);

               _result = ScanBitmap(writeableBmp);

               await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
            }

            await _mediaCapture.StopPreviewAsync();
            VideoCapture.Visibility = Visibility.Collapsed;
            CaptureImage.Visibility = Visibility.Visible;
            ScanResult.Text = _result.Text;
         }
         catch (Exception ex)
         {
            Error.Text = ex.Message;
         }
      }
        public async void InitializeAudioRecording()
        {
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
            settings.MediaCategory = MediaCategory.Other;
            settings.AudioProcessing = Windows.Media.AudioProcessing.Default;

            await _mediacapture.InitializeAsync(settings);

            //_mediacapture.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
        }
        private async Task InitializeCameraAsync()
        {
            Debug.WriteLine("InitializeCameraAsync");

            if (_mediaCapture == null)
            {
                // Attempt to get the front camera if one is available, but use any camera device if not
                var cameraDevice = await TryGetFrontCamera();

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

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

                // Register for a notification when video recording has reached the maximum time and when something goes wrong
                _mediaCapture.Failed += HandleMediaCaptureFailed;

                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");
                }

                // 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
                        _isExternalCamera = true;
                    }
                    else
                    {
                        // Camera is fixed on the device
                        _isExternalCamera = false;
                    }

                    await StartPreviewAsync();
                }
            }
        }
        public async Task InitializeCameraAsync()
        {
            if (MediaCapture == null)
            {
                // daj sve devices, slicno kao i serial
                var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                // pokusace prvo pozadinsku kameru mobitela
                DeviceInformation cameraDevice =
                    allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null &&
                    x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
                // Ako je ne nadje prva kamera koja ima onda se uzima, tj spojena usb kamera
                cameraDevice = cameraDevice ?? allVideoDevices.FirstOrDefault();
                //negdje zabiljeziti statuse kad kamera ne radi ili varijabla ili exception, sta je vise pogodno
                if (cameraDevice == null)
                {
                    internalStatus = "No camera device found.";
                    return;
                }
                //Inicijalizacija api za mediacapture
                MediaCapture = new MediaCapture();
                var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
                try
                {
                    //incijalizirati kameru
                    await MediaCapture.InitializeAsync(mediaInitSettings);
                    _isInitialized = true;
                }
                catch (UnauthorizedAccessException)
                {
                    internalStatus = ("The app was denied access to the camera");
                }
                catch (Exception ex)
                {
                    internalStatus = ("Exception when initializing MediaCapture with "+ cameraDevice.Id+ ex.ToString());
                }

                // Ako se incijalizirala, prikazati preview u preview kontroli
                if (_isInitialized)
                {
                    // Kako baratati sa naopakim kamerama, da li prednju ili zadnju kameru na mobitelu treba flipati
                    if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                    {
                        _externalCamera = true;
                    }
                    else
                    {
                        _externalCamera = false;
                        _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                    }
                    await StartPreviewAsync();
                }
            }
        }
        /// <summary>
        /// Finds the video profiles for the back camera. Then queries for a profile that supports
        /// HDR video recording. If a HDR supported video profile is located, then we configure media settings to the
        /// matching profile. Finally we initialize media capture HDR recording mode to auto.
        /// </summary>
        /// <param name="sender">Contains information regarding button that fired event</param>
        /// <param name="e">Contains state information and event data associated with the event</param>
        private async void CheckHdrSupportBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            string videoDeviceId = string.Empty;
            bool HdrVideoSupported = false;
            MediaCapture mediaCapture = new MediaCapture();
            MediaCaptureInitializationSettings mediaCaptureInitSetttings = new MediaCaptureInitializationSettings();

            // Select the first video capture device found on the back of the device
            await LogStatusToOutputBox("Querying for video capture device on back of the device that supports Video Profile");
            videoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Back);

            if (string.IsNullOrEmpty(videoDeviceId))
            {
                await LogStatus("ERROR: No Video Device Id found, verify your device supports profiles", NotifyType.ErrorMessage);
                return;
            }

            await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture,
                "Found device that supports Video Profile, Device Id:\r\n {0}", videoDeviceId));
            IReadOnlyList<MediaCaptureVideoProfile> profiles = MediaCapture.FindKnownVideoProfiles(videoDeviceId, KnownVideoProfile.VideoRecording);

            // Walk through available profiles, look for first profile with HDR supported Video Profile
            foreach (MediaCaptureVideoProfile profile in profiles)
            {
                IReadOnlyList<MediaCaptureVideoProfileMediaDescription> recordMediaDescription = profile.SupportedRecordMediaDescription;
                foreach (MediaCaptureVideoProfileMediaDescription videoProfileMediaDescription in recordMediaDescription)
                {
                    if (videoProfileMediaDescription.IsHdrVideoSupported)
                    {
                        // We've located the profile and description for HDR Video, set profile and flag
                        mediaCaptureInitSetttings.VideoProfile = profile;
                        mediaCaptureInitSetttings.RecordMediaDescription = videoProfileMediaDescription;
                        HdrVideoSupported = true;
                        await LogStatus("HDR supported video profile found, set video profile to current HDR supported profile", NotifyType.StatusMessage);
                        break;
                    }
                }

                if (HdrVideoSupported)
                {
                    break;
                }
            }

            await LogStatusToOutputBox("Initializing Media settings to HDR Supported video profile");
            await mediaCapture.InitializeAsync(mediaCaptureInitSetttings);
            if (HdrVideoSupported)
            {
                await LogStatusToOutputBox("Initializing HDR Video Mode to Auto");
                mediaCapture.VideoDeviceController.HdrVideoControl.Mode = Windows.Media.Devices.HdrVideoMode.Auto;
            }
        }
        private async void PreviewCameraFeed()
        {
            try
            {
                var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                if (cameras.Count < 1)
                {
                    MessageDialog dialog = new MessageDialog("You don't have any cameras attached to this device to use for scanning.", "Camera Not Found");
                    await dialog.ShowAsync();

                    if (Frame.CanGoBack)
                        Frame.GoBack();
                }

                MediaCaptureInitializationSettings settings = null;
                DeviceInformation camera = null;

                foreach (var item in cameras)
                {
                    if (item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back)
                    {
                        camera = item;
                        break;
                    }
                }

                if (camera == null)
                    camera = cameras[0];

                settings = new MediaCaptureInitializationSettings { VideoDeviceId = camera.Id };

                await captureManager.InitializeAsync(settings);

                this.cptCameraFeed.Source = captureManager;

                captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

                await captureManager.StartPreviewAsync();

                dispatcherTimer = new DispatcherTimer();
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 3, 0);
                dispatcherTimer.Tick += DispatcherTimer_Tick;

                dispatcherTimer.Start();
            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog("Something went wrong while decoding the QR code. Please try scanning again.", "Scanning Failed");
                dialog.ShowAsync();
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            DeviceInformationCollection oCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            switch (oCameras.Count)
            {
                case 0:
                    throw new Exception("No cameras found");
                case 1:
                    //Only front camera is available
                    Camera = oCameras[(int)CameraLocation.Front];
                    break;
                default:
                    //By default, we want the back camera
                    Camera = oCameras[(int)CameraLocation.Back];
                    break;
            }

            MediaCaptureInitializationSettings oCameraSettings = new MediaCaptureInitializationSettings();
            oCameraSettings.VideoDeviceId = Camera.Id;

            MediaCapture oCamera = new MediaCapture();
            await oCamera.InitializeAsync(oCameraSettings);

            // resolution variables
            //int iMaxResolution = 0;
            //int iHeight = 0;
            //int iWidth = 0;
            //int iSelectedIndex = 0;
            //IReadOnlyList<IMediaEncodingProperties> oAvailableResolutions = oCamera.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

            //// if no settings available, bail
            //if (oAvailableResolutions.Count < 1) return;

            //// list the different format settings
            //for (int i = 0; i < oAvailableResolutions.Count; i++)
            //{
            //    VideoEncodingProperties oProperties = (VideoEncodingProperties)oAvailableResolutions[i];
            //    if (oProperties.Width * oProperties.Height > iMaxResolution)
            //    {
            //        iHeight = (int)oProperties.Height;
            //        iWidth = (int)oProperties.Width;
            //        iMaxResolution = (int)oProperties.Width;
            //        iSelectedIndex = i;
            //    }
            //}

            //// set resolution
            //await oCamera.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, oAvailableResolutions[iSelectedIndex]);

            oMediaCapture.Source = oCamera;
            await oMediaCapture.Source.StartPreviewAsync();
        }
        private async void captureVideo_Click(object sender, RoutedEventArgs e)
        {
            var settings = new MediaCaptureInitializationSettings()
            {
                StreamingCaptureMode = StreamingCaptureMode.Video
            };
            await _mediaCapture.InitializeAsync(settings);
            _mediaCapture.Failed += MediaCapture_Failed;
            captureElement.Source = _mediaCapture;

            var effect = await _mediaCapture.AddVideoEffectAsync(new VideoEffectDefinition(typeof(SaturationVideoEffect).FullName, _effectConfiguration), MediaStreamType.VideoPreview);
            await _mediaCapture.StartPreviewAsync();
        }
Beispiel #32
0
        /// <summary>
        /// 'Initialize Audio Only' button action function
        /// Dispose existing MediaCapture object and set it up for audio only
        /// Enable or disable appropriate buttons
        /// - DISABLE 'Initialize Audio Only'
        /// - DISABLE 'Start Video Record'
        /// - DISABLE 'Take Photo'
        /// - ENABLE 'Initialize Audio and Video'
        /// - ENABLE 'Start Audio Record'
        /// </summary>
        public async Task <string> InitializeAudioOnly()
        {
            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 only...");
                mediaCapture = new MediaCapture();
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
                settings.MediaCategory        = Windows.Media.Capture.MediaCategory.Other;
                settings.AudioProcessing      = Windows.Media.AudioProcessing.Default;
                await mediaCapture.InitializeAsync(settings);

                // Set callbacks for failure and recording limit exceeded
                Debug.WriteLine("Device successfully initialized for audio recording!" + "\nPress \'Start Audio Record\' to record");
                mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
                mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);

                //TODO: Enable buttons for audio


                //TODO: Enable Audio and video Only Init button


                return("Audio initialized");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to initialize camera for audio mode: " + ex.Message);
                throw ex;
            }
        }
        public async Task<bool> Initialize() 
        {
            // 音声のみを記録するように設定する
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;

            // 録音するコンポーネントの初期化
            mMediaCapture = await InitMediaCapture(settings, MediaCaptureOnFailed, MediaCaptureOnRecordLimitationExceeded);

            // レコーディング状態を初期化完了状態に変更する
            mRecordingState.RecordingMode = RecordingModeType.Initialized;

            return (mMediaCapture != null);
        }
        public async Task InitializeAudioRecording()
        {
            _mediaCaptureManager = new MediaCapture();
            var settings = new MediaCaptureInitializationSettings();
            settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
            settings.MediaCategory = MediaCategory.Other;
            settings.AudioProcessing = AudioProcessing.Default;

            await _mediaCaptureManager.InitializeAsync(settings);

            Debug.WriteLine("Device initialized successfully");
            _mediaCaptureManager.RecordLimitationExceeded += RecordLimitationExceeded;
            _mediaCaptureManager.Failed += Failed;
        }
Beispiel #35
0
        private void InitCaptureSettings()
        {
            // Set the capture setting
            captureInitSettings = null;
            captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

            captureInitSettings.AudioDeviceId = "";

            captureInitSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
            if (deviceList.Count > 0)
            {
                captureInitSettings.AudioDeviceId = deviceList[0].Id;
            }
        }
Beispiel #36
0
        public async Task InitPreview(CaptureElement captureElement)
        {
            this.CameraCaptureElement = captureElement;
            this.CameraMediaCapture   = new MediaCapture();

            // Initialize capture settings for Video mode
            MediaCaptureInitializationSettings settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

            settings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;

            // Select proper Video device to match back camera (depending on whether or not the device has front+back cameras or only back camera)
            DeviceInformationCollection Videodevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (Videodevices.Count == 0)
            {
                // No camera available
                captureElement.Tag = "NoCamera";
                return;
            }
            else
            {
                this.CameraCaptureElement.Tag = "CameraFound";
                if (Videodevices.Count == 1)
                {
                    settings.VideoDeviceId = Videodevices[0].Id; // Videodevices[0].Id; -> back camera
                }
                else
                {
                    settings.VideoDeviceId = Videodevices[1].Id; // Videodevices[0].Id; -> front camera, Videodevices[1].Id; -> back camera
                }
            }

            // Set settings and source on Camera
            await this.CameraMediaCapture.InitializeAsync(settings);

            SetResolution();

            // Adjust camera preview orientation
            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();

            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;
            DisplayInfo_OrientationChanged(displayInfo, null);

            this.CameraCaptureElement.Source = this.CameraMediaCapture;

            // Start Camera preview
            await this.CameraMediaCapture.StartPreviewAsync();
        }
Beispiel #37
0
        public async System.Threading.Tasks.Task InitPreview(CaptureElement capturePreview)
        {
            this.capturePreview = capturePreview;
            this.captureMgr     = new MediaCapture();

            MediaCaptureInitializationSettings settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

            settings.StreamingCaptureMode = StreamingCaptureMode.Video;

            await this.captureMgr.InitializeAsync(settings);

            this.capturePreview.Source = captureMgr;
            this.captureMgr.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            await this.captureMgr.StartPreviewAsync();
        }
Beispiel #38
0
        private async void StartRecording()
        {
            try
            {
                // Get instance of the ScreenCapture object
                var screenCapture = Windows.Media.Capture.ScreenCapture.GetForCurrentView();

                // Set the MediaCaptureInitializationSettings to use the ScreenCapture as the
                // audio and video source.
                var mcis = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                mcis.VideoSource          = screenCapture.VideoSource;
                mcis.AudioSource          = screenCapture.AudioSource;
                mcis.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;

                // Initialize the MediaCapture with the initialization settings.
                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync(mcis);

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

                // Hook up events for the Failed, RecordingLimitationExceeded, and SourceSuspensionChanged events
                _mediaCapture.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(RecordingFailed);
                _mediaCapture.RecordLimitationExceeded +=
                    new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordingReachedLimit);
                screenCapture.SourceSuspensionChanged +=
                    new Windows.Foundation.TypedEventHandler <ScreenCapture, SourceSuspensionChangedEventArgs>(SourceSuspensionChanged);

                // Create a file to record to.
                var videoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("recording.mp4", CreationCollisionOption.ReplaceExisting);

                // Create an encoding profile to use.
                var profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.HD1080p);

                // Start recording
                var start_action = _mediaCapture.StartRecordToStorageFileAsync(profile, videoFile);
                start_action.Completed += CompletedStart;

                // Set a tracking variable for recording state in App.xaml.cs
                (App.Current as App).IsRecording = true;
            }
            catch (Exception ex)
            {
                NotifyUser("StartRecord Exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
Beispiel #39
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);;
        }
        private async void initAudioOnly()
        {
            try
            {
                if (mediaCapture != null)
                {
                    // Cleanup MediaCapture object
                    if (isPreviewing)
                    {
                        await mediaCapture.StopPreviewAsync();

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

                        isRecording = false;

                        recordAudio.Content = "Start Audio Record";
                    }
                    mediaCapture.Dispose();
                    mediaCapture = null;
                }

                status.Text  = "Initializing camera to capture audio only...";
                mediaCapture = new MediaCapture();
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
                settings.MediaCategory        = Windows.Media.Capture.MediaCategory.Other;
                settings.AudioProcessing      = Windows.Media.AudioProcessing.Default;

                await mediaCapture.InitializeAsync(settings);

                // Set callbacks for failure and recording limit exceeded
                status.Text          = "Device successfully initialized for audio recording!" + "\nPress \'Start Audio Record\' to record";
                mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
                mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);
                recordAudio.IsEnabled = true;
            }
            catch (Exception ex)
            {
                status.Text = "Unable to initialize camera for audio mode: " + ex.Message;
            }
        }
Beispiel #41
0
        private async Task StartPreviewAsync()
        {
            try
            {
                if (mediaCapture != null)
                {
                    await mediaCapture.StopPreviewAsync();

                    mediaCapture.Dispose();
                }
                mediaCapture = new MediaCapture();

                MediaCaptureInitializationSettings settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.AudioDeviceId        = "";
                settings.VideoDeviceId        = _SelectedVideoSource.Id;
                settings.StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo;
                settings.PhotoCaptureSource   = PhotoCaptureSource.VideoPreview;

                await mediaCapture.InitializeAsync(settings);

                mediaCapture.Failed += MediaCapture_Failed;

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

            try
            {
                PreviewControl.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();

                isPreviewing = true;
            }
            catch (System.IO.FileLoadException)
            {
                mediaCapture.CaptureDeviceExclusiveControlStatusChanged += _mediaCapture_CaptureDeviceExclusiveControlStatusChanged;
            }
        }
        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);
            }
        }
Beispiel #43
0
        private async void startCapture()
        {
            try
            {
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

                settings.VideoDeviceId        = captureDevice.Id;
                settings.StreamingCaptureMode = StreamingCaptureMode.Video;


                await mediaCaptureMgr.InitializeAsync(settings);
            }
            catch (Exception) {}

            try
            {
                cameraView.Visibility = Windows.UI.Xaml.Visibility.Visible;
                cameraElement.Source  = mediaCaptureMgr;
                await mediaCaptureMgr.StartPreviewAsync();
            }
            catch (Exception) {}
        }
        async Task initMediaCaptureAsync()
        {
            var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();

            captureInitSettings.AudioDeviceId        = DeviceInfo.Instance.Id;
            captureInitSettings.VideoDeviceId        = DeviceInfo.Instance.Id;
            captureInitSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
            captureInitSettings.PhotoCaptureSource   = Windows.Media.Capture.PhotoCaptureSource.VideoPreview;

            if (deviceList.Count > 0)
            {
                captureInitSettings.VideoDeviceId = deviceList[0].Id;
            }

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

            // Add video stabilization effect during Live Capture
            Windows.Media.Effects.VideoEffectDefinition def = new Windows.Media.Effects.VideoEffectDefinition(Windows.Media.VideoEffects.VideoStabilization);
            await mediaCapture.AddVideoEffectAsync(def, MediaStreamType.VideoRecord);

            profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Qvga);

            // Use MediaEncodingProfile to encode the profile
            System.Guid MFVideoRotationGuild = new System.Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");

            int MFVideoRotation = convertVideoRotationToMFRotation(VideoRotation.None);

            profile.Video.Properties.Add(MFVideoRotationGuild, PropertyValue.CreateInt32(MFVideoRotation));

            // add the mediaTranscoder
            var transcoder = new Windows.Media.Transcoding.MediaTranscoder();

            transcoder.AddVideoEffect(Windows.Media.VideoEffects.VideoStabilization);

            // wire to preview XAML element
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
        }
        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();
                settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
                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);
            }
        }
Beispiel #46
0
        private async void Checked()
        {
            try
            {
                var settings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
                settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Audio;
                settings.MediaCategory        = Windows.Media.Capture.MediaCategory.Other;
                settings.AudioProcessing      = Windows.Media.AudioProcessing.Default;
                await audioCapture.InitializeAsync(settings);

                StorageFolder externalDevices = KnownFolders.RemovableDevices;
                IReadOnlyList <StorageFolder> externalDrives = await externalDevices.GetFoldersAsync();

                StorageFolder usbStorage = externalDrives[0];

                //ENSURE FOLDER EXISTS
                if (await usbStorage.TryGetItemAsync("Recording") == null)
                {
                    await usbStorage.CreateFolderAsync("Recording");
                }

                string Folder_Pfad = "Recording\\" + DateTime.Now.Year.ToString();
                if (await usbStorage.TryGetItemAsync(Folder_Pfad) == null)
                {
                    await usbStorage.CreateFolderAsync(Folder_Pfad);
                }

                Folder_Pfad = Folder_Pfad + "\\" + DateTime.Now.Month.ToString();
                if (await usbStorage.TryGetItemAsync(Folder_Pfad) == null)
                {
                    await usbStorage.CreateFolderAsync(Folder_Pfad);
                }

                Folder_Pfad = Folder_Pfad + "\\" + DateTime.Now.Day.ToString();
                if (await usbStorage.TryGetItemAsync(Folder_Pfad) == null)
                {
                    await usbStorage.CreateFolderAsync(Folder_Pfad);
                }

                string Dateiname = "\\" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + " "
                                   + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + ".mp3";

                string Dateispeicher_Ort = Folder_Pfad + Dateiname;

                StorageFile recordFile = await usbStorage.CreateFileAsync(Dateispeicher_Ort, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                isRecording = true;
                //await audioCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), recordFile);

                var audioRecording = await audioCapture.PrepareLowLagRecordToStorageFileAsync(MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Medium), recordFile);

                await audioRecording.StartAsync();

                Task.Delay(10000).Wait();
                Unchecked();
            }
            catch (Exception ex)
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                    Result.Text += ex.Message;
                });
            }
        }