public async void InitMediaCapture() { mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(captureInitSettings); //test var properties = mediaCapture.VideoDeviceController; // 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 = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); profile.Video.PixelAspectRatio.Numerator = 16; profile.Video.PixelAspectRatio.Denominator = 9; // 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 //capturePreview.Source = mediaCapture; //DisplayInformation.AutoRotationPreferences = DisplayOrientations.None; }
public async Task StartAsync() { m_isRecording = true; if (m_isVideo) { var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); var rotationAngle = CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper.GetCameraCaptureOrientation()); profile.Video.Properties.Add(new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"), PropertyValue.CreateInt32(rotationAngle)); m_lowLag = await m_mediaCapture.PrepareLowLagRecordToStorageFileAsync(profile, m_file); await m_lowLag.StartAsync(); } else { var wavEncodingProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); wavEncodingProfile.Audio.BitsPerSample = 16; wavEncodingProfile.Audio.SampleRate = 48000; wavEncodingProfile.Audio.ChannelCount = 1; m_opusSink = await OpusCodec.CreateMediaSinkAsync(m_file); await m_mediaCapture.StartRecordToCustomSinkAsync(wavEncodingProfile, m_opusSink); } }
private async void recording() { try { ShowStatusMessage("Starting Record"); String fileName; fileName = VIDEO_FILE_NAME; recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); await mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, recordStorageFile); isRecording = true; recordBtn.IsEnabled = true; recordBtn.Content = "Stop Record"; ShowStatusMessage("Start Record successful"); } catch { } }
private async void StartRecord() { try { ShowStatusMessage("Starting Record"); String fileName; fileName = VIDEO_FILE_NAME; m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, m_recordStorageFile); m_bRecording = true; btnStartStopRecord1.IsEnabled = true; btnStartStopRecord1.Content = "StopRecord"; ShowStatusMessage("Start Record successful"); } catch (Exception exception) { ShowExceptionMessage(exception); } }
private async void ToggleRecording(object sender, RoutedEventArgs e) { if (VideoButton.IsChecked.Value) { CameraLabel.Text = "wait for it..."; Back.IsEnabled = false; SwitchCameraButton.IsEnabled = false; CameraButton.IsEnabled = false; VideoButton.IsEnabled = false; var folder = await KnownFolders.VideosLibrary.CreateFolderAsync("NYLT Form Capture", CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(applicant.FileName + ".mp4", CreationCollisionOption.ReplaceExisting); await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p), file); CameraLabel.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.Red); CameraLabel.Text = "recording"; isRecording = true; VideoButton.IsEnabled = true; } else { CameraLabel.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.Black); CameraLabel.Text = "saving"; await mediaCapture.StopRecordAsync(); isRecording = false; CameraLabel.Text = ""; SwitchCameraButton.IsEnabled = true; CameraButton.IsEnabled = true; Back.IsEnabled = true; } }
private async void TakeVideoAsync() { mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); if (isVideoStarted == false) { var myVideos = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Videos); StorageFile file = await myVideos.SaveFolder.CreateFileAsync("video.mp4", CreationCollisionOption.GenerateUniqueName); _mediaRecording = await mediaCapture.PrepareLowLagRecordToStorageFileAsync( MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), file); await _mediaRecording.StartAsync(); isVideoStarted = true; } else { await _mediaRecording.StopAsync(); await _mediaRecording.FinishAsync(); } }
private void loadAllVideoProperties() { //we only support standard recording profiles. _encodingProfiles = new List <MediaEncodingProfile>(); _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p)); _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p)); //720*480 _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Ntsc)); //720*576 _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Pal)); //320*240 _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga)); //640*480 _encodingProfiles.Add(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga)); var properties = device.CaptureSource.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord); SupportedFormat.Items.Clear(); _validVideoRecordProperties = new List <VideoEncodingProperties>(); foreach (var p in properties) { var pp = p as VideoEncodingProperties; if (pp.Subtype != VideoSourceSubType) { continue; } if (isEncodingPropertyInProfileList(pp, _encodingProfiles)) { _validVideoRecordProperties.Add(pp); SupportedFormat.Items.Add($"{pp.Width}*{pp.Height} {Convert.ToInt32(0.5 + pp.FrameRate.Numerator / pp.FrameRate.Denominator)}FPS"); } } }
private MediaEncodingProfile GetMediaEncoding(Resolutions resolution, VideoEncodingProperties videoEncoding) { MediaEncodingProfile mediaEncoding; if (resolution.Resolution.Width >= 2560) { mediaEncoding = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Uhd2160p); } else if (resolution.Resolution.Width <= 1280) { mediaEncoding = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); } else { mediaEncoding = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p); } mediaEncoding.Video.FrameRate.Denominator = videoEncoding.FrameRate.Denominator; mediaEncoding.Video.FrameRate.Numerator = videoEncoding.FrameRate.Numerator; mediaEncoding.Video.Width = resolution.Resolution.Width; mediaEncoding.Video.Height = resolution.Resolution.Height; long inputVideo = videoEncoding.Width * videoEncoding.Height; long outputVideo = resolution.Resolution.Width * resolution.Resolution.Height; mediaEncoding.Video.Bitrate = (uint)(videoEncoding.Bitrate * outputVideo / inputVideo); return(mediaEncoding); }
private async Task <MediaCapture> StartRecording(string fileName) { var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture); var camerDeviceId = devices.FirstOrDefault()?.Id; var captureSettings = new MediaCaptureInitializationSettings { VideoDeviceId = camerDeviceId, AudioDeviceId = string.Empty, PhotoCaptureSource = PhotoCaptureSource.VideoPreview, StreamingCaptureMode = StreamingCaptureMode.Video }; var mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(captureSettings); var def = new Windows.Media.Effects.VideoEffectDefinition(Windows.Media.VideoEffects.VideoStabilization); await mediaCapture.AddVideoEffectAsync(def, MediaStreamType.VideoRecord); var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga); var storageFolder = await KnownFolders.RemovableDevices .GetFolderAsync("E:\\"); var storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); await mediaCapture.StartRecordToStorageFileAsync(profile, storageFile); return(mediaCapture); }
private async void StartMediaCaptureRecord_Click(object sender, RoutedEventArgs e) { StartCaptureElementRecord.IsEnabled = false; // Skip if no camera var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (devices.Count == 0) { return; } StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectsTestApp.MediaCapture.mp4", CreationCollisionOption.ReplaceExisting); var capture = new MediaCapture(); await capture.InitializeAsync(new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Video }); var definition = await CreateEffectDefinitionAsync( (VideoEncodingProperties)capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord) ); await capture.AddEffectAsync(MediaStreamType.VideoRecord, definition.ActivatableClassId, definition.Properties); await capture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga), destination); await Task.Delay(3000); await capture.StopRecordAsync(); StartCaptureElementRecord.IsEnabled = true; }
private async void UpdateTorchStatus(bool isOn) { try { await InitTorchControl(); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine($"{nameof(UpdateTorchStatus)}: {exception.Message}"); } if (!isOn && _torchControl.Enabled) { _torchControl.Enabled = false; _mediaCapture.Dispose(); return; } if (isOn && !_torchControl.Enabled) { var videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga); var videoStorageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("temp.mp4", CreationCollisionOption.ReplaceExisting); await _mediaCapture.StartRecordToStorageFileAsync(videoEncodingProperties, videoStorageFile); _torchControl.Enabled = true; } }
async void Transcode(StorageFile input, bool hide = false) { try { _cts = new CancellationTokenSource(); _Profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); //_Profile.Video.Width = 720; //_Profile.Video.Height = 1080; //_Profile.Video.Bitrate = 70000; //_Profile.Audio.Bitrate = 96000; //_Profile.Audio.SampleRate = 44100; //_Profile.Audio. _OutputFile = await localFolder.CreateFileAsync(13.GenerateRandomStringStatic() + ".mp4", CreationCollisionOption.GenerateUniqueName); var preparedTranscodeResult = await _Transcoder.PrepareFileTranscodeAsync(input, _OutputFile, _Profile); Hide(); _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default; if (preparedTranscodeResult.CanTranscode) { var progress = new Progress <double>(TranscodeProgress); //stopwatch.Reset(); //stopwatch.Start(); //MASettings.GPVisibility = Visibility.Visible; //StopRadioButton.Visibility = Visibility.Visible; await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress); } else { ("Failed to start.\r\nError: " + preparedTranscodeResult.FailureReason).PrintDebug(); } } catch { } }
private async System.Threading.Tasks.Task StartRecordAsync() { try { IsRecording = true; //if camera does not support lowlag record and lowlag photo at the same time enable TakePhoto button after recording IsCaptureEnabled = m_mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported; string fileName = "LumiaImagingVideo.mp4"; var recordStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); // Calculate rotation angle, taking mirroring into account if necessary var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation()); recordProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle)); Debug.WriteLine("Starting recording..."); await m_mediaCapture.StartRecordToStorageFileAsync(recordProfile, recordStorageFile); } catch (Exception exception) { Debug.Assert(true, string.Format("Failed to start record video. {0}", exception.Message)); IsRecording = false; } }
private MediaEncodingProfile getVideoEncoding() { VideoEncodingQuality quality = VideoEncodingQuality.Auto; myQuality = "Auto"; switch (videoQuality.SelectedIndex) { case 2: quality = VideoEncodingQuality.HD1080p; myQuality = "1080p"; break; case 3: quality = VideoEncodingQuality.HD720p; myQuality = "720p"; break; case 4: quality = VideoEncodingQuality.Vga; myQuality = "VGA"; break; default: break; } myEncoding = (videoType == null || videoType.SelectedIndex == 0) ? "MP4" : "WMV"; return((videoType == null || videoType.SelectedIndex == 0) ? MediaEncodingProfile.CreateMp4(quality) : MediaEncodingProfile.CreateWmv(quality)); }
public async Task <bool> StartRecordingAsync() { if (Initialized && PreviewStarted && !RecordingStarted) { #if WINDOWS_PHONE_APP MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); recordProfile.Video.FrameRate.Numerator = _hfrVideoEncodingProperties.FrameRate.Numerator; recordProfile.Video.FrameRate.Denominator = _hfrVideoEncodingProperties.FrameRate.Denominator; double factor = (double)(recordProfile.Video.FrameRate.Numerator) / (recordProfile.Video.FrameRate.Denominator * 4); recordProfile.Video.Bitrate = (uint)(recordProfile.Video.Width * recordProfile.Video.Height * factor); await MediaCapture.StartRecordToStreamAsync(recordProfile, _recordingStream); #else MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); await MediaCapture.StartRecordToStreamAsync(recordProfile, _recordingStream); #endif // Get camera's resolution VideoEncodingProperties resolution = (VideoEncodingProperties)_videoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord); ResolutionWidth = (int)resolution.Width; ResolutionHeight = (int)resolution.Height; Messenger.SettingsChangedFlag = true; await MediaCapture.AddEffectAsync(RecordMediaStreamType, BufferTransformActivationId, Properties); RecordingStarted = true; } return(RecordingStarted); }
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed private void RenderCompositionToFile(Windows.Storage.StorageFile file) { var mp4Profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); var saveOperation = _mediaComposition.RenderToFileAsync(file, MediaTrimmingPreference.Fast, mp4Profile); saveOperation.Progress = new AsyncOperationProgressHandler <TranscodeFailureReason, double>((info, progress) => { Helper.UIUtility.RunAsync(() => { ProgressVM.Progress = progress; }); }); saveOperation.Completed = new AsyncOperationWithProgressCompletedHandler <TranscodeFailureReason, double>((info, status) => { var results = info.GetResults(); if (results != TranscodeFailureReason.None || status != AsyncStatus.Completed) { Helper.UIUtility.RunAsync(() => { ProgressVM.Status = ProgressStatus.Failed; }); } else { Helper.UIUtility.RunAsync(() => { ProgressVM.Status = ProgressStatus.Success; }); } }); }
void GetCustomProfile() { if (_UseMp4) { _Profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Wvga); } else { _Profile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Wvga); } try { _Profile.Video.Width = UInt32.Parse(VideoW.Text); _Profile.Video.Height = UInt32.Parse(VideoH.Text); _Profile.Video.Bitrate = UInt32.Parse(VideoBR.Text); _Profile.Video.FrameRate.Numerator = UInt32.Parse(VideoFR.Text); _Profile.Video.FrameRate.Denominator = 1; _Profile.Audio.BitsPerSample = UInt32.Parse(AudioBPS.Text); _Profile.Audio.ChannelCount = UInt32.Parse(AudioCC.Text); _Profile.Audio.Bitrate = UInt32.Parse(AudioBR.Text); _Profile.Audio.SampleRate = UInt32.Parse(AudioSR.Text); } catch (Exception exception) { TranscodeError(exception.Message); _Profile = null; } }
/// <summary> /// Transcode a video file to an animated GIF image /// </summary> /// <param name="source">a video file</param> /// <param name="destination">an empty GIF image</param> /// <param name="arguments">transcode parameters</param> /// <returns>an async action</returns> public IAsyncAction TranscodeAsync(StorageFile source, StorageFile destination, ValueSet arguments) { return(AsyncInfo.Run(async delegate(CancellationToken token) { object value; var videoProperties = await source.Properties.GetVideoPropertiesAsync(); var width = videoProperties.Width; var height = videoProperties.Height; if (arguments != null && arguments.TryGetValue("Quality", out value)) { var qualityString = value.ToString(); VideoEncodingQuality quality; if (Enum.TryParse(qualityString, out quality)) { var profile = MediaEncodingProfile.CreateMp4(quality); width = profile.Video.Width; height = profile.Video.Height; } } await TranscodeGifAsync(source, destination, width, height); })); }
/// <summary> /// Records an MP4 video to a StorageFile and adds rotation metadata to it /// </summary> /// <returns></returns> private async Task StartRecordingAsync() { try { // Create storage file for the capture var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName); var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); // Calculate rotation angle, taking mirroring into account if necessary var rotationAngle = CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper.GetCameraCaptureOrientation()); encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle)); Debug.WriteLine("Starting recording to " + videoFile.Path); await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile); _isRecording = true; Debug.WriteLine("Started recording!"); } catch (Exception ex) { // File I/O errors are reported as exceptions Debug.WriteLine("Exception when starting video recording: " + ex.ToString()); } }
/// <summary> /// Records an MP4 video to a StorageFile and adds rotation metadata to it /// </summary> /// <returns></returns> private async Task StartRecordingAsync() { try { // Create storage file in Pictures Library var videoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName); var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); // Calculate rotation angle, taking mirroring into account if necessary var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation()); encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle)); Debug.WriteLine("Starting recording..."); await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile); _isRecording = true; Debug.WriteLine("Started recording!"); } catch (Exception ex) { // File I/O errors are reported as exceptions Debug.WriteLine("Exception when starting video recording: {0}", ex.ToString()); } }
private async void RecordButtonClickHandler(object sender, RoutedEventArgs e) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { if (isRecording) { return; } recordButton.Visibility = Visibility.Collapsed; stopRecordButton.Visibility = Visibility.Visible; playButton.IsEnabled = false; StartRecordTimerCount(); if (await SetupRecordProcess()) { if (UIHelper.GetDeviceFamily() != "Windows.Mobile") { await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), buffer); } else { //No mp3 or wma on win mobile so we use mp4 instead, still give better compressed size than using raw format await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), buffer); } if (isRecording) { ThrowInvalidOperantionException(); return; } isRecording = true; } }); }
public async Task StartCaptureVideo(string subfolder = "CameraService") { if (DefaultManager == null) { throw new Exception("Not initialized"); } if (Capturing) { throw new InvalidOperationException("Already capturing"); } var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); var folder = await KnownFolders.VideosLibrary.CreateFolderAsync(subfolder, CreationCollisionOption.OpenIfExists); var name = $"{DateTime.Now.ToString("yymmddhhnnss")}.mp4"; try { CaptureVideoFile = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName); await DefaultManager.StartRecordToStorageFileAsync(profile, CaptureVideoFile); Capturing = true; } catch { throw; } CaptureVideoStarted?.Invoke(this, EventArgs.Empty); }
//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); } }
/// <summary> /// /// </summary> /// <returns></returns> private async Task startRecoding() { if (isPreview) { timer.Cancel(); timer = null; isPreview = false; await capture.StopPreviewAsync(); //録画開始 isRecording = true; videoFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); MediaEncodingProfile profile = null; profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga); await capture.StartRecordToStorageFileAsync(profile, videoFile); isRecording = true; Debug.WriteLine("Start Recording"); //15秒後に録画停止 recordingTimer = new Timer(stopRecording, null, 15000, 15000); } }
async Task InitMediaCaptureAsync() { var captureInitSettings = new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Video, PhotoCaptureSource = PhotoCaptureSource.VideoPreview }; if (deviceList.Count > 0) { captureInitSettings.VideoDeviceId = deviceList[0].Id; } mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); await AddVideoStabilization().ConfigureAwait(false); profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga); var MFVideoRotationGuild = GetMediaEncodingProfileGUID(); int MFVideoRotation = ConvertVideoRotationToMFRotation(VideoRotation.None); profile.Video.Properties.Add(MFVideoRotationGuild, PropertyValue.CreateInt32(MFVideoRotation)); var transcoder = new Windows.Media.Transcoding.MediaTranscoder(); transcoder.AddVideoEffect(Windows.Media.VideoEffects.VideoStabilization); DisplayInformation.AutoRotationPreferences = DisplayOrientations.None; }
private async Task BeginRecording() { while (true) { try { Debug.WriteLine($"Recording started"); var memoryStream = new InMemoryRandomAccessStream(); await _mediaCap.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga), memoryStream); await Task.Delay(TimeSpan.FromSeconds(5)); await _mediaCap.StopRecordAsync(); Debug.WriteLine($"Recording finished, {memoryStream.Size} bytes"); memoryStream.Seek(0); CurrentVideo.Id = Guid.NewGuid(); CurrentVideo.Data = new byte[memoryStream.Size]; await memoryStream.ReadAsync(CurrentVideo.Data.AsBuffer(), (uint)memoryStream.Size, InputStreamOptions.None); Debug.WriteLine($"Bytes written to stream"); _signal.Set(); _signal.Reset(); } catch (Exception ex) { Debug.WriteLine($"StartRecording -> {ex.Message}"); break; } } }
public async void StartVideoRecordingOnThread(StreamSocket _socket) { //Make sure the MediaCapture object is initialized await CheckSetUp(); Streamer streamer = new Streamer(_socket); // When the streamer is connected, create a new Output stream using the streamer isRecording = true; while (true) { InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga), stream); await Task.Delay(TimeSpan.FromSeconds(1)); await _mediaCapture.StopRecordAsync(); stream.Seek(0); Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size); await stream.ReadAsync(buffer, (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None); streamer.WriteToSocketUsingReader(buffer); } }
async private void ToggleRecordVideo(object sender, RoutedEventArgs e) { //initialize capture MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings(); settings.StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo; _capture = new MediaCapture(); await _capture.InitializeAsync(settings); //start preview capture_element.Source = _capture; await _capture.StartPreviewAsync(); //start capturing media var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga); var feedback_folder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("VideoFeedback", CreationCollisionOption.OpenIfExists); _target_file = await feedback_folder.CreateFileAsync("video message.mp4", CreationCollisionOption.GenerateUniqueName); await _capture.StartRecordToStorageFileAsync(profile, _target_file); //show the flyout menu media_message.Visibility = Visibility.Collapsed; media.Stop(); //stop playback since we are recording FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement); }
/// <summary> /// Start video recording /// </summary> /// <returns></returns> private async Task StartVideoRecordingAsync() { try { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => PhotoButton.IsEnabled = false); if (_mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) { ImageEncodingProperties imageEncodingProperties = ImageEncodingProperties.CreateJpeg(); _lowLagPhotoCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(imageEncodingProperties); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => PhotoButton.IsEnabled = true); } var mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); var folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("Cam360", CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync("test.mp4", CreationCollisionOption.GenerateUniqueName); await _mediaCapture.StartRecordToStorageFileAsync(mediaEncodingProfile, file); } catch (Exception ex) { string errorMessage = string.Format("StartVideoRecording did not complete: {0}", ex.Message); Debug.Write(errorMessage); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await new MessageDialog(errorMessage).ShowAsync(); }); } }
internal async void btnStartStopRecord_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { String fileName; EnableButton(false, "StartStopRecord"); if (!m_bRecording) { ShowStatusMessage("Starting Record"); fileName = VIDEO_FILE_NAME; m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, m_recordStorageFile); m_bRecording = true; SwitchRecordButtonContent(); EnableButton(true, "StartStopRecord"); ShowStatusMessage("Start Record successful"); } else { ShowStatusMessage("Stopping Record"); await m_mediaCaptureMgr.StopRecordAsync(); m_bRecording = false; EnableButton(true, "StartStopRecord"); SwitchRecordButtonContent(); ShowStatusMessage("Stop record successful"); if (!m_bSuspended) { var stream = await m_recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ShowStatusMessage("Record file opened"); ShowStatusMessage(this.m_recordStorageFile.Path); playbackElement1.AutoPlay = true; playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType); playbackElement1.Play(); } } } catch (Exception ex) { ShowExceptionMessage(ex); m_bRecording = false; SwitchRecordButtonContent(); EnableButton(true, "StartStopRecord"); } }