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 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); }
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; } }
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; } }
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"); } } }
/// <summary> /// Initializes a new instance of the <see cref="Reader" /> class. /// </summary> /// <param name="capture">MediaCapture instance.</param> /// <param name="width">Capture frame width.</param> /// <param name="height">Capture frame height.</param> public Reader(MediaCapture capture, uint width, uint height) { this.capture = capture; this.encodingProps = new ImageEncodingProperties { Subtype = "BMP", Width = width, Height = height}; this.barcodeFound = false; this.cancelSearch = new CancellationTokenSource(); }
protected override void OnNavigatedTo(NavigationEventArgs e) { captureManager = new MediaCapture(); reader = new BarcodeReader(); PreviewCameraFeed(); }
private async void Loaded(object sender, RoutedEventArgs e) { MediaCapture capMana = new MediaCapture(); await capMana.InitializeAsync(); Webcam_Logitech.Source = capMana; await capMana.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(); } }
/// <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; }
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(); }
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); }
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 void mediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) { var action = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { progressText.Text = "MediaCapture failed: " + errorEventArgs.Message; }); }
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"; }
/// <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 FaceTrackerProxy (Canvas canvas, MainPage page, CaptureElement capture, MediaCapture mediacapture ) { if (this.faceTracker == null) { this.faceTracker = FaceTracker.CreateAsync().AsTask().Result; } rootPage = page; VisualizationCanvas = canvas; this.VisualizationCanvas.Children.Clear(); mediaCapture = mediacapture; var deviceController = mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; currentState = ScenarioState.Streaming; // Ensure the Semaphore is in the signalled state. this.frameProcessingSemaphore.Release(); // Use a 66 milisecond interval for our timer, i.e. 15 frames per second TimeSpan timerInterval = TimeSpan.FromMilliseconds(200); this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval); }
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 }
public ViewModelMain(ref CaptureElement cameraControlView) { CameraControl = cameraControlView; TakePhotoManager = new MediaCapture(); var task = CameraTest_task(); var task2 = PictureLoading_task(); CameraViewCommand = new Pomocnicze.RelayCommand(pars => CameraViewButton()); ImageListCommand = new Pomocnicze.RelayCommand(pars => ShowImagesList_async()); ShareCommand = new Pomocnicze.RelayCommand(pars => ShareButton()); PictureTapCommand = new Pomocnicze.RelayCommand(pars => SetNextPicture()); Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested +=BackRequested; DataTransferManager ShareManager = DataTransferManager.GetForCurrentView(); ShareManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.ShareImageHandler); CameraButtonName = "Camera View"; ImageListButtonName = "Images List"; ShareButtonName = "Share"; ShareButtonIsEnable = true; }
private async void cameraCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) { // It's safest to return this back onto the UI thread to show the message dialog. MessageDialog dialog = new MessageDialog(errorEventArgs.Message); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { await dialog.ShowAsync(); }); }
//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); } }
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); } }
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"); }
public async Task InitializePreview(CaptureElement captureElement) { captureManager = new MediaCapture(); var cameraID = await GetCameraID(Panel.Back); if (cameraID == null) { return; } await captureManager.InitializeAsync(new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Video, PhotoCaptureSource = PhotoCaptureSource.Photo, AudioDeviceId = string.Empty, VideoDeviceId = cameraID.Id }); await captureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution()); captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees); StartPreview(captureElement); }
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; }
public async Task InitializeAsync() { _mediaCapture = new MediaCapture(); await _mediaCapture.InitializeAsync(); _imageEncodingProperties = ImageEncodingProperties.CreateJpeg(); }
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(); } }
public ViewfinderPage() { InitializeComponent(); _navigationHelper = new NavigationHelper(this); _photoCaptureManager = new MediaCapture(); _dataContext = FilterEffects.DataContext.Instance; }
private async void Page_Loaded(object sender, RoutedEventArgs e) { MediaCaptureInitializationSettings set = new MediaCaptureInitializationSettings(); set.StreamingCaptureMode = StreamingCaptureMode.Video; mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(set); }
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; }
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()); } }
/// <summary> /// Callback function if Recording Limit Exceeded /// </summary> /// <param name="currentCaptureObject"></param> public async void mediaCapture_RecordLimitExceeded(Windows.Media.Capture.MediaCapture currentCaptureObject) { try { if (isRecording) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { try { status.Text = "Stopping Record on exceeding max record duration"; await mediaCapture.StopRecordAsync(); isRecording = false; recordAudio.Content = "Start Audio Record"; recordVideo.Content = "Start Video Record"; if (mediaCapture.MediaCaptureSettings.StreamingCaptureMode == StreamingCaptureMode.Audio) { status.Text = "Stopped record on exceeding max record duration: " + audioFile.Path; } else { status.Text = "Stopped record on exceeding max record duration: " + recordStorageFile.Path; } } catch (Exception e) { status.Text = e.Message; } }); } } catch (Exception e) { status.Text = e.Message; } }
/// <summary> /// Callback function if Recording Limit Exceeded /// </summary> /// <param name="currentCaptureObject"></param> private async void mediaCapture_RecordLimitExceeded(Windows.Media.Capture.MediaCapture currentCaptureObject) { try { if (isRecording) { await Task.Run(async() => { try { Debug.WriteLine("Stopping Record on exceeding max record duration"); await mediaCapture.StopRecordAsync(); isRecording = false; if (mediaCapture.MediaCaptureSettings.StreamingCaptureMode == StreamingCaptureMode.Audio) { Debug.WriteLine("Stopped record on exceeding max record duration: " + audioFile.Path); } else { Debug.WriteLine("Stopped record on exceeding max record duration: " + recordStorageFile.Path); } } catch (Exception e) { Debug.WriteLine("Error: " + e.Message); throw e; } }); } } catch (Exception e) { Debug.WriteLine("Error: " + e.Message); throw e; } }
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; } }
public void RecordingReachedLimit(Windows.Media.Capture.MediaCapture currentCaptureObject) { _recordingStatus = RecordingStatus.failed; NotifyUser("RecordLimitationExceeded event raised.", NotifyType.ErrorMessage); }
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); } }
public void RecordingFailed(Windows.Media.Capture.MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure) { _recordingStatus = RecordingStatus.failed; NotifyUser("RecordFailed Event raised. ", NotifyType.ErrorMessage); }
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> }
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); }
// </SnippetMediaCaptureLowLagPhotoCaptureCode> async private void InitalizeCamera(MediaCapture captureManager) { captureManager = new MediaCapture(); await captureManager.InitializeAsync(); }
async private void InitCamera_Click(object sender, RoutedEventArgs e) { captureManager = new MediaCapture(); await captureManager.InitializeAsync(); }