private async void ButtonBase_OnClick(object sender, RoutedEventArgs e) { mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); storageFolder = ApplicationData.Current.LocalFolder; storageFile = await storageFolder.CreateFileAsync("test.mp3", CreationCollisionOption.GenerateUniqueName); lowLagMedia = await mediaCapture.PrepareLowLagRecordToStorageFileAsync( MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High), storageFile); await lowLagMedia.StartAsync(); }
/* * Method for writing the video and audio files */ private async void WriteFileAsync(YouTubeVideo video) { StorageFile mp4StorageFile = await _storageFolder.CreateFileAsync(video.FullName, CreationCollisionOption.ReplaceExisting); // Store the video as a MP4 await FileIO.WriteBytesAsync(mp4StorageFile, video.GetBytes()); _mp3FileName = mp4StorageFile.Name.Substring(0, mp4StorageFile.Name.Length - 14); StorageFile mp3StorageFile = await _storageFolder.CreateFileAsync(_mp3FileName + ".mp3", CreationCollisionOption.ReplaceExisting); var profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); await ToAudioAsync(mp4StorageFile, mp3StorageFile, profile); }
private async void BothPlay() { var myVideos = await 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(); Load(); }
private async void CaptureClick(object sender, RoutedEventArgs e) { if (CaptureButton.IsChecked.Value) { var file = await KnownFolders.CameraRoll.CreateFileAsync("Capture.mp4", CreationCollisionOption.GenerateUniqueName); await _capture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), file); } else { await _capture.StopRecordAsync(); } }
MediaEncodingProfile CreateMediaEncodingProfile(StorageFile file) { switch (file.FileType.ToString().ToLowerInvariant()) { case ".wma": return(MediaEncodingProfile.CreateWma(AudioEncodingQuality.High)); case ".mp3": return(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High)); case ".wav": return(MediaEncodingProfile.CreateWav(AudioEncodingQuality.High)); default: throw new ArgumentException(); } }
/// <summary> /// 'Start Audio Record' button click action function /// Button name is changes to 'Stop Audio Record' once recording is started /// Records audio to a file in the default account video folder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void recordAudio_Click(object sender, RoutedEventArgs e) { recordAudio.IsEnabled = false; playbackElement3.Source = null; try { if (recordAudio.Content.ToString() == "Start Audio Record") { audioFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(AUDIO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); status.Text = "Audio storage file preparation successful"; MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto); await mediaCapture.StartRecordToStorageFileAsync(recordProfile, audioFile); isRecording = true; recordAudio.IsEnabled = true; recordAudio.Content = "Stop Audio Record"; status.Text = "Audio recording in progress... press \'Stop Audio Record\' to stop"; } else { status.Text = "Stopping audio recording..."; await mediaCapture.StopRecordAsync(); isRecording = false; recordAudio.IsEnabled = true; recordAudio.Content = "Start Audio Record"; var stream = await audioFile.OpenAsync(Windows.Storage.FileAccessMode.Read); status.Text = "Playback recorded audio: " + audioFile.Path; playbackElement3.AutoPlay = true; playbackElement3.SetSource(stream, audioFile.FileType); playbackElement3.Play(); } } catch (Exception ex) { status.Text = ex.Message; Cleanup(); } finally { recordAudio.IsEnabled = true; } }
/// <summary> /// 'Start Video Record' button click action function /// Button name is changed to 'Stop Video Record' once recording is started /// Records video to a file in the default account videos folder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async Task <string> RecordVideo(StorageFile file) { try { if (!isRecording) { Debug.WriteLine("Initialize video recording"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); this.recordStorageFile = file; await mediaCapture.StartRecordToStorageFileAsync(recordProfile, recordStorageFile); isRecording = true; string message = "Video recording in progress.."; Debug.WriteLine(message); return(message); } else { Debug.WriteLine("Stopping video recording..."); await mediaCapture.StopRecordAsync(); var stream = await recordStorageFile.OpenReadAsync(); /* * playbackElement.AutoPlay = true; * playbackElement.SetSource(stream, recordStorageFile.FileType); * playbackElement.Play(); */ Debug.WriteLine("Playing recorded video" + recordStorageFile.Path); isRecording = false; return(recordStorageFile.Name); } } catch (Exception ex) { if (ex is System.UnauthorizedAccessException) { string message = "Unable to play recorded video; video recorded successfully to: " + recordStorageFile.Path; Debug.WriteLine(message); return(message); } else { Debug.WriteLine(ex.Message); Cleanup(); return(ex.Message); } } }
async Task Start() { md = new MediaCapture(); await md.InitializeAsync(); var video = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Videos); StorageFile file = await video.SaveFolder.CreateFileAsync("video.mp4", CreationCollisionOption.GenerateUniqueName); recorder = await md.PrepareLowLagRecordToStorageFileAsync( MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), file); await recorder.StartAsync(); }
private async void MediaCapture_buttonPlayVideo() { MediaEncodingProfile video = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Video.mp4", CreationCollisionOption.ReplaceExisting); await mediaCap.StartRecordToStorageFileAsync(video, file); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += Timer_Tick; timer.Start(); sw.Start(); }
public static Task <bool> TryTranscodeAudioAsync(IStorageFile input, IStorageFile output, bool hq, IProgress <double?> progress, CancellationToken token = default) { try { Analytics.TrackEvent("MediaTranscoding_AudioTranscodeRequested"); var profile = MediaEncodingProfile.CreateMp3(hq ? AudioEncodingQuality.High : AudioEncodingQuality.Medium); return(TryTranscodeMediaAsync(input, output, profile, progress, token)); } finally { Analytics.TrackEvent("MediaTranscoding_AudioTranscodeComplete"); } }
public async void ExtractAudio(string artist, string title, StorageFile videoFile, StorageFile audioFile) { if (this.transcoder == null) { this.transcoder = new MediaTranscoder(); this.encodingProfile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); } var preparedTranscodeResult = await this.transcoder.PrepareFileTranscodeAsync(videoFile, audioFile, this.encodingProfile); await preparedTranscodeResult.TranscodeAsync(); await TagStorageFile(artist, title, audioFile); }
public async void StartRecord(object sender, RoutedEventArgs e) { if (isRecording) { return; } // 開始錄音 await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), buffer); isRecording = true; recordStartTime = DateTime.UtcNow; timer.Start(); }
public async void Record() { //Wait for init method to complet await Init(); //Wait for capture await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto), buffer); if (Recording) { throw new InvalidOperationException("cannot excute two records at the same time"); } Recording = true; }
private async void TranscodeWithEffect() { var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; openPicker.FileTypeFilter.Add(".wmv"); openPicker.FileTypeFilter.Add(".mp4"); StorageFile sourceFile = await openPicker.PickSingleFileAsync(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; savePicker.DefaultFileExtension = ".mp4"; savePicker.SuggestedFileName = "New Video"; savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".mp4" }); StorageFile destinationFile = await savePicker.PickSaveFileAsync(); MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); //<SnippetTrancodeWithEffect> MediaTranscoder transcoder = new MediaTranscoder(); // Using the in-box video stabilization effect works //VideoStabilizationEffectDefinition videoEffect = new VideoStabilizationEffectDefinition(); //transcoder.AddVideoEffect(videoEffect.ActivatableClassId); // My custom effect throws an exception var customEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect", new PropertySet() { { "FadeValue", .25 } }); transcoder.AddVideoEffect(customEffectDefinition.ActivatableClassId); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(sourceFile, destinationFile, mediaEncodingProfile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); } //</SnippetTrancodeWithEffect> }
private async void OnStartRecord(object sender, RoutedEventArgs e) { rdbPhoto.IsEnabled = rdbRecord.IsEnabled = false; // 取得視訊目錄 StorageFolder vdfolder = KnownFolders.VideosLibrary; // 新檔名 string newFilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp4"; // 建立新檔案 StorageFile newFile = await vdfolder.CreateFileAsync(newFilename, CreationCollisionOption.ReplaceExisting); // 開始錄制 await _capture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), newFile); btnRec.Content = "停止錄制"; }
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 = AUDIO_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.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto); await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, this.m_recordStorageFile); m_bRecording = true; SwitchRecordButtonContent(); EnableButton(true, "StartStopRecord"); ShowStatusMessage("Start Record successful"); } else { stopRack.Visibility = Visibility.Collapsed; ShowStatusMessage("Stopping Record"); await m_mediaCaptureMgr.StopRecordAsync(); m_bRecording = false; EnableButton(true, "StartStopRecord"); SwitchRecordButtonContent(); ShowStatusMessage("Stop record successful"); } } catch (Exception exception) { EnableButton(true, "StartStopRecord"); ShowExceptionMessage(exception); m_bRecording = false; } }
private static async void TranscodeFile(MediaEncodingProfile profile, TimeSpan trimStartTime, TimeSpan trimStopTime, StorageFile srcFile, StorageFile destFile, Action <StorageFile, ulong> callback, Action <double> progressCallback, Action <IAsyncActionWithProgress <double> > faultCallback) { profile = profile ?? await MediaEncodingProfile.CreateFromFileAsync(srcFile); var transcoder = new MediaTranscoder { TrimStartTime = trimStartTime, TrimStopTime = trimStopTime }; var prepareOp = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile); //Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("TranscodeFile\nvideo=[{0}x{1} {2}]\naudio=[{3}]\ntrim_start={4} trim_end={5}", profile.Video.Width, profile.Video.Height, profile.Video.Bitrate, profile.Audio != null ? profile.Audio.Bitrate : 0, trimStartTime, trimStopTime)); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += (result, progress) => { progressCallback.SafeInvoke(progress); }; transcodeOp.Completed += async(o, e) => { var properties = await destFile.GetBasicPropertiesAsync(); var size = properties.Size; TranscodeComplete(o, e, () => callback(destFile, size), faultCallback); }; } else { faultCallback.SafeInvoke(null); switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.CodecWasNotFound, AppResources.Error, MessageBoxButton.OK)); break; case TranscodeFailureReason.InvalidProfile: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.ProfileIsInvalid, AppResources.Error, MessageBoxButton.OK)); break; default: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.UnknownFailure, AppResources.Error, MessageBoxButton.OK)); break; } } }
private int intDelay = 200; // Record Time in millesecond... // Short time - increase repetet noise ... // Long time - create echo ... // I think 200ms is optimum ... // If you use headphones - best time will be 500..1000ms ... private async void btnStart_Click(object sender, RoutedEventArgs e) { blnStart = true; btnStart.Visibility = Visibility.Collapsed; btnStop.Visibility = Visibility.Visible; textBlock.Visibility = Visibility.Visible; mediaCaptureAudioPrimery = 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 = Windows.Media.AudioProcessing.Default; // Use only Default await mediaCaptureAudioPrimery.InitializeAsync(settings); recordProfile = MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Low); while (blnStart) // Repeate untile stop ... { try { msIRAS0 = new MemoryStream(); streamIRAS0 = msIRAS0.AsRandomAccessStream(); // New Stream ... await mediaCaptureAudioPrimery.StartRecordToStreamAsync(recordProfile, streamIRAS0); // write audio in first stream ... await Task.Delay(intDelay); await mediaCaptureAudioPrimery.StopRecordAsync(); // Stop first stream await PlayThreadMethod(streamIRAS0); // Play from first stream msIRAS1 = new MemoryStream(); streamIRAS1 = msIRAS0.AsRandomAccessStream(); // Second Stream ... await mediaCaptureAudioPrimery.StartRecordToStreamAsync(recordProfile, streamIRAS1); // sweetch stream ... to second stream ... await Task.Delay(intDelay); await mediaCaptureAudioPrimery.StopRecordAsync(); await PlayThreadMethod(streamIRAS1); // Play Second Streem } catch (Exception ex) { Stop(); } } }
public async Task <Signal> LoadSignalAsync(StorageFile file) { Stream stream; // if user opens WAV-file then we load its contents directly if (file.Name.EndsWith("wav", StringComparison.OrdinalIgnoreCase)) { stream = await file.OpenStreamForReadAsync(); } // otherwise transcode to wave else { var transcoder = new MediaTranscoder(); var profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium); var temporaryFile = await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(TemporaryWaveFile) as StorageFile; if (temporaryFile != null) { await temporaryFile.DeleteAsync(StorageDeleteOption.Default); } temporaryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(TemporaryWaveFile); if (temporaryFile == null) { return(null); } var preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync(file, temporaryFile, profile); if (preparedTranscodeResult.CanTranscode) { await preparedTranscodeResult.TranscodeAsync(); } else { await new MessageDialog("Error: could not convert to wave!").ShowAsync(); } stream = await temporaryFile.OpenStreamForReadAsync(); } var signal = new Signal(); await Task.Run(() => signal.Load(stream)); return(signal); }
async void Start() { if (!IsWorking) { try { if (mediaCapture != null) { try { mediaCapture.Failed -= MediaCapture_Failed; mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded; } catch { } try { mediaCapture.Dispose(); mediaCapture = null; } catch { } } Duration = 0; mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); mediaCapture.Failed += MediaCapture_Failed; mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded; if (file != null) { try { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch { } } var name = Helper.GenerateRandomString(); file = await localFolder.CreateFileAsync($"{name}.m4a", CreationCollisionOption.GenerateUniqueName); await mediaCapture.StartRecordToStorageFileAsync( MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Low), file); IsWorking = true; StopGrid.Visibility = Visibility.Visible; RecordGrid.Visibility = Visibility.Collapsed; RootTimer.Start(); } catch (Exception ex) { ex.PrintException("Start"); } } }
async private void ToggleRecord2(object sender, RoutedEventArgs e) { var btn_record_audio = sender as ToggleButton; if (btn_record_audio.IsChecked == false) { _graph_record.Stop(); _graph_record.Dispose(); await PlayAudio(_target_file); //using the media element to play the sound //var raf_stream = await _target_file.OpenReadAsync(); //media.SetSource(raf_stream, ""); //media.Play(); } else { //initialize the audio graph for recording and then start recording AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media); settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency; CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); if (result.Status == AudioGraphCreationStatus.Success) { _graph_record = result.Graph; //setup the input var input_node = (await _graph_record.CreateDeviceInputNodeAsync(Windows.Media.Capture.MediaCategory.Other)).DeviceInputNode; //setup the output (place where audio will be recorded to) var feedback_folder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("AudioFeedback", CreationCollisionOption.OpenIfExists); _target_file = await feedback_folder.CreateFileAsync("audio message.mp3", CreationCollisionOption.GenerateUniqueName); var profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); var file_output_node = (await _graph_record.CreateFileOutputNodeAsync(_target_file, profile)).FileOutputNode; //direct the input to the output input_node.AddOutgoingConnection(file_output_node); media.Stop(); //stop playback since we are recording _graph_record.Start(); } else { await new MessageDialog("Could not initialize recorder").ShowAsync(); } } }
public async void Record(CaptureElement preview) { await init(); preview.Source = capture; await capture.StartPreviewAsync(); await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), buffer); if (Recording) { throw new InvalidOperationException("cannot excute two records at the same time"); } Recording = true; }
private async Task InitialiseAudioFileOutputNode() { var outputProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Low); outputProfile.Audio = AudioEncodingProperties.CreatePcm(this.SAMPLE_RATE, this.CHANNEL, this.BITS_PER_SAMPLE); var outputResult = await this._audioGraph.CreateFileOutputNodeAsync(this._storageFile, outputProfile); if (outputResult.Status != AudioFileNodeCreationStatus.Success) { throw new MicrophoneServiceException("AudioFileNode creation error !"); } this._audioFileOutputNode = outputResult.FileOutputNode; }
private async Task InitialiseAudioFeed() { var defaultAudioCaptureId = MediaDevice.GetDefaultAudioCaptureId(AudioDeviceRole.Default); var microphone = await DeviceInformation.CreateFromIdAsync(defaultAudioCaptureId); var inputProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); var inputResult = await this._audioGraph.CreateDeviceInputNodeAsync(MediaCategory.Media, inputProfile.Audio, microphone); if (inputResult.Status != AudioDeviceNodeCreationStatus.Success) { throw new MicrophoneServiceException("AudioDeviceNode creation error !"); } inputResult.DeviceInputNode.AddOutgoingConnection(this._audioFileOutputNode); }
private async Task StartRecordingToCustomSink() { // Use the MP4 preset to an obtain H.264 video encoding profile var mep = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga); mep.Audio = null; mep.Container = null; if (previewEncodingProperties != null) { mep.Video.Width = previewEncodingProperties.Width; mep.Video.Height = previewEncodingProperties.Height; } await device.StartRecordingAsync(mep); }
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); // Video sources providing more than about 250 megapixels per second require the // H.264 encoder to be set to level 5.2. Information about H.264 encoding levels: // https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels // Windows doesn't always set the higher level automatically so it should be set // explicitly to avoid encoding failures. Constants needed to set the encoding level: // https://docs.microsoft.com/en-us/windows/win32/medfound/mf-mt-video-level // https://docs.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vlevel if (_UseMp4) { const int c_PixelsPerSecondRequiringLevel52 = 250000000; if (_Profile.Video.Width * _Profile.Video.Height * _Profile.Video.FrameRate.Numerator / _Profile.Video.FrameRate.Denominator > c_PixelsPerSecondRequiringLevel52) { _Profile.Video.Properties[MediaFoundationConstants.MF_MT_VIDEO_LEVEL] = (UInt32)MediaFoundationConstants.eAVEncH264VLevel.eAVEncH264VLevel5_2; } } } catch (Exception exception) { TranscodeError(exception.Message); _Profile = null; } }
public static MediaEncodingProfile CreateVideoEncodingProfileFromProps(bool hq, VideoProperties props) { var width = (double)props.Width; var height = (double)props.Height; var bitrate = hq ? (uint)2_000_000 : 1_115_000; double maxWidth = App.RoamingSettings.Read(VIDEO_WIDTH, 854); double maxHeight = App.RoamingSettings.Read(VIDEO_HEIGHT, 480); Drawing.ScaleProportions(ref width, ref height, maxWidth, maxHeight); bitrate = App.RoamingSettings.Read(VIDEO_BITRATE, bitrate); if (width == 0) { width = maxWidth; } if (height == 0) { height = maxHeight; } var profile = new MediaEncodingProfile() { Container = new ContainerEncodingProperties() { Subtype = MediaEncodingSubtypes.Mpeg4 }, Video = new VideoEncodingProperties() { Width = (uint)(Math.Round(width / 2.0) * 2), Height = (uint)(Math.Round(height / 2.0) * 2), Subtype = MediaEncodingSubtypes.H264, Bitrate = bitrate }, Audio = new AudioEncodingProperties() { Bitrate = App.RoamingSettings.Read(AUDIO_BITRATE, 192u), BitsPerSample = 16, ChannelCount = 2, SampleRate = App.RoamingSettings.Read(AUDIO_SAMPLERATE, 44100u), Subtype = MediaEncodingSubtypes.Aac } }; return(profile); }
public async Task Init() { Recording = false; // Selecionar o dispositivo para gravar e reproduzir var devices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); var devicesIn = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioCaptureSelector()); outputDevice = devices[0]; // Configurações de gravações AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media) { //QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency, PrimaryRenderDevice = outputDevice, }; CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); graph = result.Graph; deviceOutputNode = (await graph //Criar nó de saída (Reprodução no headset) .CreateDeviceOutputNodeAsync()) .DeviceOutputNode; deviceInputNode = (await graph //Criar nó de entrada (Microfone) - Real-time communication .CreateDeviceInputNodeAsync(MediaCategory.Communications, graph.EncodingProperties, devicesIn[0])) .DeviceInputNode; // Criar o arquivo para ser armazenado o PCM gravado direto do microfone StorageFile pcmfile = await KnownFolders .MusicLibrary .CreateFileAsync("PCM_original.wav", Windows.Storage.CreationCollisionOption.ReplaceExisting); // PCM 16bits com 44,1kHZ com 96kbps MediaEncodingProfile profile = MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Medium); pcmFileNode = (await graph // Criar nó do arquivo de saída .CreateFileOutputNodeAsync(pcmfile, profile)) .FileOutputNode; // Conectar os nós de reprodução e do arquivo PCM ao nó do microfone // Ou seja, passar os sinais para o fone reproduzir e o arquivo armazenar ao mesmo tempo deviceInputNode.AddOutgoingConnection(pcmFileNode); deviceInputNode.AddOutgoingConnection(deviceOutputNode); }
private async void Initialize() { this.Loaded += InstantReplayPage_Loaded; viewModel = new InstantReplayPageViewModel(); viewModel.Initialize(inkCanvas); viewModel.TogglePlayPauseEvent += TogglePlayPause; Scrubber.ValueChanged += Scrubber_ValueChanged; var file = await viewModel.StartCapture(null); //var profiles = MediaCapture.FindAllVideoProfiles(cameraId); MediaCapture capture = new MediaCapture(); var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture); var captureInitSettings = new MediaCaptureInitializationSettings(); var profile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Auto); captureInitSettings.StreamingCaptureMode = StreamingCaptureMode.Video; captureInitSettings.VideoDeviceId = devices[0].Id; mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(captureInitSettings); storageFile = await KnownFolders.VideosLibrary.CreateFileAsync("InstantReplayCapture.wmv", CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.Add(storageFile); storageFileStream = await storageFile.OpenStreamForWriteAsync(); fileStream = new DVRRandomAccessStream(storageFileStream); lowLagRecord = await mediaCapture.PrepareLowLagRecordToStreamAsync(profile, fileStream); await lowLagRecord.StartAsync(); VideoPlayer.SetSource(fileStream.PlaybackStream, storageFile.ContentType); VideoPlayer.PartialMediaFailureDetected += VideoPlayer_PartialMediaFailureDetected; VideoPlayer.MediaFailed += VideoPlayer_MediaFailed; VideoPlayer.CurrentStateChanged += (s, e) => { Debug.WriteLine("State: " + VideoPlayer.CurrentState); }; VideoPlayer.MediaEnded += VideoPlayer_MediaEnded; this.DataContext = viewModel; }
public async Task RecordAsync() { if (mediaCapture != null) { throw new InvalidOperationException("Recording already in progress"); } try { var captureSettings = new MediaCaptureInitializationSettings() { StreamingCaptureMode = StreamingCaptureMode.Audio }; await InitMediaCapture(captureSettings); } catch (Exception ex) { CanRecordAudio = false; DeleteMediaCapture(); if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException)) { throw ex.InnerException; } throw; } var localFolder = ApplicationData.Current.LocalFolder; var fileName = Path.GetRandomFileName(); var fileOnDisk = await localFolder.CreateFileAsync(fileName); try { await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), fileOnDisk); // await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), fileOnDisk); } catch { CanRecordAudio = false; DeleteMediaCapture(); throw; } audioFilePath = fileOnDisk.Path; }