public static async Task PlayAudio(StorageFile file) { await AudioDevices(); _isAudioPlaying = true; CreateAudioFileInputNodeResult fileInputResult = await audioflow.CreateFileInputNodeAsync(file); if (AudioFileNodeCreationStatus.Success != fileInputResult.Status) { // Cannot read input file Debug.WriteLine(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString())); _isAudioPlaying = false; return; } if (!_isAudioPlaying) { Debug.WriteLine("Error detected!"); return; } fileInput = fileInputResult.FileInputNode; fileInput.FileCompleted += FileInput_FileCompleted; try { fileInput.AddOutgoingConnection(deviceOuput); } catch (Exception e) { Debug.WriteLine(e.ToString()); } fileInput.StartTime = TimeSpan.FromSeconds(0); audioflow.Start(); _isAudioPlaying = false; }
private async void initGraph() { AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media); CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); graph = result.Graph; // Create a device output node CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync(); deviceOutput = deviceOutputNodeResult.DeviceOutputNode; FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); StorageFile file = await GetPackagedFile(null, "audio.mp3"); CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); fileInput = fileInputResult.FileInputNode; fileInput.AddOutgoingConnection(deviceOutput); graph.Start(); }
private async Task SelectInputFile() { StorageFile file = await GetPackagedFile(null, "audio.mp3"); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputNodeResult = await graph.CreateFileInputNodeAsync(file); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot read file return; } fileInputNode = fileInputNodeResult.FileInputNode; fileInputNode.AddOutgoingConnection(deviceOutputNode); // Event Handler for file completion fileInputNode.FileCompleted += FileInput_FileCompleted; // Enable the button to start the graph // Create the custom effect and apply to the FileInput node AddCustomEffect(); }
private async void File_Click(object sender, RoutedEventArgs e) { // If another file is already loaded into the FileInput node if (fileInput != null) { // Release the file and dispose the contents of the node fileInput.Dispose(); // Stop playback since a new file is being loaded. Also reset the button UI if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".m4a"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (AudioFileNodeCreationStatus.Success != fileInputResult.Status) { // Cannot read input file rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage); return; } fileInput = fileInputResult.FileInputNode; fileInput.AddOutgoingConnection(deviceOutput); fileButton.Background = new SolidColorBrush(Colors.Green); if (fileInput.Duration.TotalSeconds < 3) { // Imported file is too short rootPage.NotifyUser(String.Format("This scenario requires a sound file which is longer than 3 seconds"), NotifyType.ErrorMessage); return; } // Trim the file: set the start time to 3 seconds from the beginning // fileInput.EndTime can be used to trim from the end of file fileInput.StartTime = TimeSpan.FromSeconds(3); // Enable buttons in UI to start graph, loop and change playback speed factor graphButton.IsEnabled = true; loopToggle.IsEnabled = true; playSpeedSlider.IsEnabled = true; }
private async void File_Click(object sender, RoutedEventArgs e) { // If another file is already loaded into the FileInput node if (fileInputNode != null) { // Release the file and dispose the contents of the node fileInputNode.Dispose(); // Stop playback since a new file is being loaded. Also reset the button UI if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".wav"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (fileInputResult.Status != AudioFileNodeCreationStatus.Success) { // Error reading the input file rootPage.NotifyUser(String.Format("Can't read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage); return; } // File loaded successfully. Enable these buttons in the UI graphButton.IsEnabled = true; echoEffectToggle.IsEnabled = true; reverbEffectToggle.IsEnabled = true; limiterEffectToggle.IsEnabled = true; eqToggle.IsEnabled = true; fileInputNode = fileInputResult.FileInputNode; fileInputNode.AddOutgoingConnection(deviceOutputNode); rootPage.NotifyUser("Successfully loaded input file", NotifyType.StatusMessage); fileButton.Background = new SolidColorBrush(Colors.Green); // Create the four inbox effects CreateEchoEffect(); CreateReverbEffect(); CreateLimiterEffect(); CreateEqEffect(); }
private async void MainGraph_QuantumProcessed(AudioGraph sender, object args) { try { this.Position = mainInputNode.Position; if (NextJump != null) { if (NextJump != null && Position >= NextJump.Origin - NextJump.CrossFade && Position <= NextJump.Origin && !IsFading && NextJump.Song == mainSong) { IsFading = true; subInputNode = mainInputNode; subSong = mainSong; mainSong = NextJump.TargetSong ?? NextJump.Song; mainInputNode = await mainSong.Song.CreateNode(graph); mainInputNode.AddOutgoingConnection(outputNode); mainInputNode.StartTime = NextJump.TargetTime - (NextJump.Origin - subInputNode.Position); mainInputNode.OutgoingGain = 0; mainInputNode.Start(); } if (IsFading && subInputNode != null) { var fadePosition = (NextJump.Origin - subInputNode.Position); var fadeTime = NextJump.CrossFade; var percentage = Math.Min(1.0, Math.Max(0.0, fadePosition.TotalSeconds / fadeTime.TotalSeconds)); subInputNode.OutgoingGain = percentage; mainInputNode.OutgoingGain = 1.0 - percentage; } if (Position > NextJump.Origin && IsFading && subInputNode != null) { mainInputNode.OutgoingGain = 1.0; subInputNode.Stop(); subInputNode.RemoveOutgoingConnection(outputNode); subInputNode.Dispose(); subInputNode = null; subSong = null; NextJump = NextJump.NextDefaultJump; IsFading = false; } } } catch (Exception e) { App.Log(e); Recover(); } }
private async void File1_Click(object sender, RoutedEventArgs e) { // If another file is already loaded into the FileInput node if (fileInputNode1 != null) { // Release the file and dispose the contents of the node fileInputNode1.Dispose(); // Stop playback since a new file is being loaded. Also reset the button UI if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".wav"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file1 = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file1 == null) { return; } CreateAudioFileInputNodeResult fileInputNodeResult = await graph.CreateFileInputNodeAsync(file1); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot read input file rootPage.NotifyUser(String.Format("Can't read input file1 because {0}", fileInputNodeResult.Status.ToString()), NotifyType.ErrorMessage); return; } fileInputNode1 = fileInputNodeResult.FileInputNode; // Since we are going to play two files simultaneously, set outgoing gain to 0.5 to prevent clipping fileInputNode1.AddOutgoingConnection(submixNode, 0.5); // The graph might already be playing, so set up UI accordingly if (graphButton.Content.Equals("Stop Graph")) { audioPipe1.Fill = new SolidColorBrush(Colors.Blue); } // UI tasks: enable buttons, show status message and change color of the input node box graphButton.IsEnabled = true; echoEffectToggle.IsEnabled = true; rootPage.NotifyUser("Loaded File 1", NotifyType.StatusMessage); fileButton1.Background = new SolidColorBrush(Colors.Green); }
public async Task <bool> SetSourceAsync(StorageFile file) { Stop(); _inputNode?.Dispose(); _inputNode = null; var result = await _audioGraph.CreateFileInputNodeAsync(file); LastStatus = result.Status.ToString(); if (result.Status != AudioFileNodeCreationStatus.Success) { return(false); } lock (this) { try { _inputNode = result.FileInputNode; var invalidDuration = TimeSpan.FromMilliseconds(50); if (_inputNode.Duration < invalidDuration) { return(false); } _inputNode.AddOutgoingConnection(_outputNode); ThresoldDuration = _inputNode.Duration - invalidDuration; _inputNode.EffectDefinitions.Add(CreateEchoEffect()); _inputNode.EffectDefinitions.Add(CreateLimiterEffect()); _inputNode.EffectDefinitions.Add(CreateReverbEffect()); _inputNode.EffectDefinitions.Add(CreateEqualizerEffect()); IsEchoEffectEnabled = IsEchoEffectEnabled; IsReverbEffectEnabled = IsReverbEffectEnabled; IsLimiterEffectEnabled = IsLimiterEffectEnabled; IsEQEffectEnabled = IsEQEffectEnabled; } catch (Exception) { return(false); } } if (AutoPlay) { Play(); } return(true); }
private async void PlayAudioGraph_Click(object sender, RoutedEventArgs e) { // If another file is already loaded into the FileInput node if (fileInput != null) { // Release the file and dispose the contents of the node fileInput.Dispose(); } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".m4a"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (AudioFileNodeCreationStatus.Success != fileInputResult.Status) { // Cannot read input file Logging.SingleInstance.LogMessage("Cannot read input file because " + fileInputResult.Status); return; } fileInput = fileInputResult.FileInputNode; if (fileInput.Duration <= TimeSpan.FromSeconds(3)) { // Imported file is too short Logging.SingleInstance.LogMessage("Please pick an audio file which is longer than 3 seconds " + fileInputResult.Status); fileInput.Dispose(); fileInput = null; return; } fileInput.AddOutgoingConnection(deviceOutput); // Trim the file: set the start time to 3 seconds from the beginning // fileInput.EndTime can be used to trim from the end of file fileInput.StartTime = TimeSpan.FromSeconds(3); }
public async Task Play(SongViewModel song) { if (mainInputNode == null) { mainInputNode = await song.Song.CreateNode(graph); mainSong = song; NextJump = mainSong.Jumps.FirstOrDefault(); mainInputNode.AddOutgoingConnection(outputNode); graph.Start(); IsPlaying = true; } else if (IsPlaying) { var jump = new JumpViewModel(mainSong) { Origin = mainInputNode.Position + TimeSpan.FromSeconds(5), TargetSong = song, TargetTime = TimeSpan.FromSeconds(5), CrossFade = TimeSpan.FromSeconds(5) }; if (mainInputNode.Duration < jump.Origin) { jump.Origin = mainInputNode.Duration; jump.CrossFade = mainInputNode.Duration - mainInputNode.Position; jump.TargetTime = jump.CrossFade; } NextJump = jump; } else { if (mainInputNode != null) { mainInputNode.RemoveOutgoingConnection(outputNode); mainInputNode.Dispose(); mainInputNode = null; mainSong = null; } if (subInputNode != null) { subInputNode.RemoveOutgoingConnection(outputNode); subInputNode.Dispose(); subInputNode = null; subSong = null; } IsFading = false; await Play(song); } }
public async Task LoadFileIntoGraph(StorageFile audioFile) { CreateAudioFileInputNodeResult audioFileInputResult = await this._audioGraph.CreateFileInputNodeAsync(audioFile); if (audioFileInputResult.Status != AudioFileNodeCreationStatus.Success) { throw new Exception("File failed to load into graph."); } _fileInputNode = audioFileInputResult.FileInputNode; _fileInputNode.AddOutgoingConnection(_deviceOutputNode); CreateAndAddEchoEffect(); }
/// <summary> /// Plays audio from specified file. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public async Task PlayFromFile(string fileName) { lock (this) { isInitialized.CheckIfFulfills("Speaker", "initialized", true); isPlaying = true; } await CreateFileInputNode(fileName); fileInput.AddOutgoingConnection(deviceOutput); audioGraph.Start(); }
private async Task SelectInputFile() { // If another file is already loaded into the FileInput node if (fileInputNode != null) { // Release the file and dispose the contents of the node fileInputNode.Dispose(); // Stop playback since a new file is being loaded. Also reset the button UI if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputNodeResult = await graph.CreateFileInputNodeAsync(file); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot read file rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputNodeResult.Status.ToString()), NotifyType.ErrorMessage); return; } fileInputNode = fileInputNodeResult.FileInputNode; fileInputNode.AddOutgoingConnection(deviceOutputNode); fileButton.Background = new SolidColorBrush(Colors.Green); // Event Handler for file completion fileInputNode.FileCompleted += FileInput_FileCompleted; // Enable the button to start the graph graphButton.IsEnabled = true; // Create the custom effect and apply to the FileInput node AddCustomEffect(); }
private async Task LoadAudioFromFile(StorageFile file) { // We initialize an instance of AudioGraph AudioGraphSettings settings = new AudioGraphSettings( Windows.Media.Render.AudioRenderCategory.Media ); CreateAudioGraphResult result1 = await AudioGraph.CreateAsync(settings); if (result1.Status != AudioGraphCreationStatus.Success) { ShowMessage("AudioGraph creation error: " + result1.Status.ToString()); } audioGraph = result1.Graph; if (audioGraph == null) return; // We initialize FileInputNode CreateAudioFileInputNodeResult result2 = await audioGraph.CreateFileInputNodeAsync(file); if (result2.Status != AudioFileNodeCreationStatus.Success) { ShowMessage("FileInputNode creation error: " + result2.Status.ToString()); } fileInputNode = result2.FileInputNode; if (fileInputNode == null) return; // We read audio file encoding properties to pass them to FrameOutputNode creator AudioEncodingProperties audioEncodingProperties = fileInputNode.EncodingProperties; // We initialize FrameOutputNode and connect it to fileInputNode frameOutputNode = audioGraph.CreateFrameOutputNode(audioEncodingProperties); fileInputNode.AddOutgoingConnection(frameOutputNode); // We add a handler achiving the end of a file fileInputNode.FileCompleted += FileInput_FileCompleted; // We add a handler which will transfer every audio frame into audioData audioGraph.QuantumStarted += AudioGraph_QuantumStarted; // We initialize audioData int numOfSamples = (int)Math.Ceiling( (decimal)0.0000001 * fileInputNode.Duration.Ticks * fileInputNode.EncodingProperties.SampleRate ); audioData = new float[numOfSamples]; audioDataCurrentPosition = 0; // We start process which will read audio file frame by frame // and will generated events QuantumStarted when a frame is in memory audioGraph.Start(); }
private async Task SelectInputFile() { if (fileInputNode != null) { fileInputNode.Dispose(); if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".m4a"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); if (file == null) { return; } CreateAudioFileInputNodeResult fileInputNodeResult = await graph.CreateFileInputNodeAsync(file); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { NotifyUser(String.Format("Cannot read input file because {0}", fileInputNodeResult.Status.ToString()), NotifyType.ErrorMessage); return; } fileInputNode = fileInputNodeResult.FileInputNode; fileInputNode.AddOutgoingConnection(deviceOutputNode); fileButton.Background = new SolidColorBrush(Colors.Green); fileInputNode.FileCompleted += FileInput_FileCompleted; graphButton.IsEnabled = true; AddCustomEffect(); }
private async void openFile() { // If another file is already loaded into the FileInput node if (fileInput != null) { // Release the file and dispose the contents of the node fileInput.Dispose(); } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".m4a"); filePicker.ViewMode = PickerViewMode.Thumbnail; // StorageFile file = await filePicker.PickSingleFileAsync(); StorageFile file = await GetPackagedFile(null, "alarm.mp3"); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (AudioFileNodeCreationStatus.Success != fileInputResult.Status) { // Cannot read input file return; } fileInput = fileInputResult.FileInputNode; fileInput.AddOutgoingConnection(deviceOutput); // Trim the file: set the start time to 3 seconds from the beginning // fileInput.EndTime can be used to trim from the end of file fileInput.StartTime = TimeSpan.FromSeconds(0); // MediaPlayer player = MediaPlayer.; }
public async Task LoadFileAsync(StorageFile file) { CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (fileInputResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot read input file //rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage); return; } fileInputNode = fileInputResult.FileInputNode; if (fileInputNode.Duration <= TimeSpan.FromSeconds(3)) { // Imported file is too short //rootPage.NotifyUser("Please pick an audio file which is longer than 3 seconds", NotifyType.ErrorMessage); fileInputNode.Dispose(); fileInputNode = null; return; } fileInputNode.AddOutgoingConnection(deviceOutput); //fileButton.Background = new SolidColorBrush(Colors.Green); // Trim the file: set the start time to 3 seconds from the beginning // fileInput.EndTime can be used to trim from the end of file //fileInput.StartTime = TimeSpan.FromSeconds(3); // Enable buttons in UI to start graph, loop and change playback speed factor //graphButton.IsEnabled = true; //loopToggle.IsEnabled = true; //playSpeedSlider.IsEnabled = true; if (WaveformRenderer != null) { WaveformBridgeDefinition definition = new WaveformBridgeDefinition(); definition.Renderer = WaveformRenderer; fileInputNode.EffectDefinitions.Add(definition); } IsPaused = true; }
private async Task PlayMyMusic() { var file = await StorageFile.GetFileFromPathAsync(fil[0].Path); //var file = await KnownFolders.MusicLibrary.GetFileAsync("smalltest.flac"); CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (fileInputResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot create graph //rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage); return; } fileInput = fileInputResult.FileInputNode; fileInput.AddOutgoingConnection(deviceOutput); //fileInput.LoopCount = 10; graph.Start(); }
private async void SecondFileButtonClick(object sender, RoutedEventArgs e) { if (_second == null) { var fileInputNodeResult = await SelectInputFile(); _second = fileInputNodeResult.FileInputNode; _second.AddOutgoingConnection(_subMixNode); SecondFileButton.Content = "Stop second file"; } else if (_second.OutgoingConnections.Count >= 1) { _second.RemoveOutgoingConnection(_subMixNode); SecondFileButton.Content = "Resume second file"; } else { _second.AddOutgoingConnection(_subMixNode); SecondFileButton.Content = "Stop second file"; } }
private void SelectInputFile() { StorageFile file = this.GetPackagedFile(null, "audio.mp3").Result; // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputNodeResult = graph.CreateFileInputNodeAsync(file).GetResults(); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // Cannot read file return; } fileInputNode = fileInputNodeResult.FileInputNode; fileInputNode.AddOutgoingConnection(deviceOutputNode); // Event Handler for file completion fileInputNode.FileCompleted += FileInput_FileCompleted; }
private async Task Play() { if (IsPlaying) { Pause(); return; } if (_audioGraph == null) { var settings = new AudioGraphSettings(AudioRenderCategory.Media) { PrimaryRenderDevice = SelectedDevice }; var createResult = await AudioGraph.CreateAsync(settings); if (createResult.Status != AudioGraphCreationStatus.Success) { return; } _audioGraph = createResult.Graph; _audioGraph.UnrecoverableErrorOccurred += OnAudioGraphError; } if (_deviceOutputNode == null) { var deviceResult = await _audioGraph.CreateDeviceOutputNodeAsync(); if (deviceResult.Status != AudioDeviceNodeCreationStatus.Success) { return; } _deviceOutputNode = deviceResult.DeviceOutputNode; } if (_frameOutputNode == null) { _frameOutputNode = _audioGraph.CreateFrameOutputNode(); _audioGraph.QuantumProcessed += GraphOnQuantumProcessed; } if (_fileInputNode == null) { if (CurrentPlayingFile == null) { return; } var fileResult = await _audioGraph.CreateFileInputNodeAsync(CurrentPlayingFile); if (fileResult.Status != AudioFileNodeCreationStatus.Success) { return; } _fileInputNode = fileResult.FileInputNode; _fileInputNode.AddOutgoingConnection(_deviceOutputNode); _fileInputNode.AddOutgoingConnection(_frameOutputNode); Duration = _fileInputNode.Duration; _fileInputNode.PlaybackSpeedFactor = PlaybackSpeed / 100.0; _fileInputNode.OutgoingGain = Volume / 100.0; _fileInputNode.FileCompleted += FileInputNodeOnFileCompleted; } Debug.WriteLine($" CompletedQuantumCount: {_audioGraph.CompletedQuantumCount}"); Debug.WriteLine($"SamplesPerQuantum: {_audioGraph.SamplesPerQuantum}"); Debug.WriteLine($"LatencyInSamples: {_audioGraph.LatencyInSamples}"); var channelCount = (int)_audioGraph.EncodingProperties.ChannelCount; _fftProvider = new FftProvider(channelCount, FftSize.Fft2048); _audioGraph.Start(); IsPlaying = true; }
LoadAudioFromFile( StorageFile file, IProgress <string> status) { _finished = false; status.Report("Reading audio file"); // Initialize FileInputNode var inputNodeCreationResult = await _audioGraph.CreateFileInputNodeAsync(file); if (inputNodeCreationResult.Status != AudioFileNodeCreationStatus.Success) { return(inputNodeCreationResult); } _fileInputNode = inputNodeCreationResult.FileInputNode; // Read audio file encoding properties to pass them //to FrameOutputNode creator var audioEncodingProperties = _fileInputNode.EncodingProperties; // Initialize FrameOutputNode and connect it to fileInputNode _frameOutputNode = _audioGraph.CreateFrameOutputNode( audioEncodingProperties ); _frameOutputNode.Stop(); _fileInputNode.AddOutgoingConnection(_frameOutputNode); // Add a handler for achiving the end of a file _fileInputNode.FileCompleted += FileInput_FileCompleted; // Add a handler which will transfer every audio frame into audioData _audioGraph.QuantumStarted += FileInput_QuantumStarted; // Initialize audioData var numOfSamples = (int)Math.Ceiling( (decimal)0.0000001 * _fileInputNode.Duration.Ticks * _fileInputNode.EncodingProperties.SampleRate ); if (audioEncodingProperties.ChannelCount == 1) { SetAudioData(new AudioDataMono(new float[numOfSamples])); } else { SetAudioData(new AudioDataStereo(new float[numOfSamples], new float[numOfSamples])); } _audioDataCurrentPosition = 0; // Start process which will read audio file frame by frame // and will generated events QuantumStarted when a frame is in memory _audioGraph.Start(); // didn't find a better way to wait for data while (!_finished) { await Task.Delay(50); } // crear status line status.Report(""); return(inputNodeCreationResult); }
private async void Toggle_Click(object sender, RoutedEventArgs e) { if (_state == PlaybackState.Paused) { if (_currentPlaying != null && _currentPlaying._state == PlaybackState.Playing) { _currentPlaying.Toggle_Click(null, null); } if (ViewModel is TLMessage message && message.Media is TLMessageMediaDocument documentMedia) { var document = documentMedia.Document as TLDocument; if (document != null) { var fileName = document.GetFileName(); if (File.Exists(FileUtils.GetTempFileName(fileName)) == false) { _state = PlaybackState.Loading; UpdateGlyph(); var manager = UnigramContainer.Current.ResolveType <IDownloadAudioFileManager>(); var download = await manager.DownloadFileAsync(fileName, document.DCId, document.ToInputFileLocation(), document.Size).AsTask(documentMedia.Document.Download()); } if (message.IsMediaUnread && !message.IsOut) { var vector = new TLVector <int> { message.Id }; if (message.Parent is TLChannel channel) { TelegramEventAggregator.Instance.Publish(new TLUpdateChannelReadMessagesContents { ChannelId = channel.Id, Messages = vector }); MTProtoService.Current.ReadMessageContentsAsync(channel.ToInputChannel(), vector, affected => { message.IsMediaUnread = false; message.RaisePropertyChanged(() => message.IsMediaUnread); }); } else { TelegramEventAggregator.Instance.Publish(new TLUpdateReadMessagesContents { Messages = vector }); MTProtoService.Current.ReadMessageContentsAsync(vector, affected => { message.IsMediaUnread = false; message.RaisePropertyChanged(() => message.IsMediaUnread); }); } } var settings = new AudioGraphSettings(AudioRenderCategory.Media); settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency; var result = await AudioGraph.CreateAsync(settings); if (result.Status != AudioGraphCreationStatus.Success) { return; } _graph = result.Graph; Debug.WriteLine("Graph successfully created!"); var file = await FileUtils.GetTempFileAsync(fileName); var fileInputNodeResult = await _graph.CreateFileInputNodeAsync(file); if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success) { return; } var deviceOutputNodeResult = await _graph.CreateDeviceOutputNodeAsync(); if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { return; } _deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode; _fileInputNode = fileInputNodeResult.FileInputNode; _fileInputNode.AddOutgoingConnection(_deviceOutputNode); _fileInputNode.FileCompleted += OnFileCompleted; _graph.Start(); _timer.Start(); _state = PlaybackState.Playing; UpdateGlyph(); _displayRequest.RequestActive(); _currentPlaying = this; Slide.Maximum = _fileInputNode.Duration.TotalMilliseconds; Slide.Value = 0; } } } else if (_state == PlaybackState.Playing) { _graph?.Stop(); _timer?.Stop(); _state = PlaybackState.Paused; UpdateGlyph(); _displayRequest.RequestRelease(); } }
// Async Speak output of a text private async Task PlayAsyncLow(SoundBite soundBite) { _playing = true; // locks additional calls for Speak until finished talking this bit if (!_canPlay || _audioGraph == null || _deviceOutputNode == null) { LOG.LogError($"PlayAsyncLow: Some items do not exist: cannot play..\n [{_audioGraph}] [{_deviceOutputNode}]"); await EndOfSound( ); return; } // don't reload if the sound is already in use if (soundBite.Melody != _soundInUse?.Melody) { // if a prev. Node exists, remove it if (_fileInputNode != null) { _audioGraph.Stop( ); _fileInputNode.FileCompleted -= _fileInputNode_FileCompleted; _fileInputNode.RemoveOutgoingConnection(_deviceOutputNode); _fileInputNode.Dispose( ); _fileInputNode = null; } // set new sound _sound = _installedSounds.Where(x => x.Melody == soundBite.Melody).FirstOrDefault( ); if (_sound == null) { LOG.LogError($"PlayAsyncLow: Melody has no Audiofile: {soundBite.Melody} - cannot play"); await EndOfSound( ); return; } StorageFile file = await StorageFile.CreateStreamedFileAsync($"{_sound.Id}.{_sound.SType}", StreamedFileWriter, null); // create the InputNode var resultAF = await _audioGraph.CreateFileInputNodeAsync(file); if (resultAF.Status != AudioFileNodeCreationStatus.Success) { LOG.LogError($"PlayAsyncLow: AudioFileNodeCreationStatus creation: {resultAF.Status}" + $"\nExtError: {resultAF.ExtendedError}"); await EndOfSound( ); return; } _fileInputNode = resultAF.FileInputNode; _fileInputNode.FileCompleted += _fileInputNode_FileCompleted; _fileInputNode.AddOutgoingConnection(_deviceOutputNode); _audioGraph.Start( ); _soundInUse = _sound.AsCopy( ); } // we capture problems through Exceptions here - the settings and restrictions seem not complete in the Docs try { // Play it // cannot start after prev end - so set it null and seek to start of file _fileInputNode.StartTime = null; _fileInputNode.EndTime = null; // cannot start after prev end - so set it null _fileInputNode.Seek(new TimeSpan(0)); // have to seek to Start, we cannot assign a StartTime before the current Position // only now we can set any new start and end... (that is not in the documents...) _fileInputNode.StartTime = TimeSpan.FromSeconds(soundBite.Tone * _soundInUse.ToneStep_sec); _fileInputNode.EndTime = _fileInputNode.StartTime + TimeSpan.FromSeconds((soundBite.Duration < 0) ? _soundInUse.ToneDuration_sec : soundBite.Duration); _fileInputNode.OutgoingGain = soundBite.Volume; _fileInputNode.LoopCount = (int)soundBite.Loops; // counts down in the Completed Callback - track completeness there (not in docu...) _fileInputNode.PlaybackSpeedFactor = soundBite.SpeedFact; // Plays in the current Thread - cannot be waited for in the same thread _fileInputNode.Start( ); //_audioGraph.Start( ); } catch (Exception e) { LOG.LogError($"PlayAsyncLow: Sample Setup caused an Exception\n{e.Message}"); await EndOfSound( ); } }
private async void File_Click(object sender, RoutedEventArgs e) { // If another file is already loaded into the FileInput node if (fileInput != null) { // Release the file and dispose the contents of the node fileInput.Dispose(); // Stop playback since a new file is being loaded. Also reset the button UI if (graphButton.Content.Equals("Stop Graph")) { TogglePlay(); } } FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary; filePicker.FileTypeFilter.Add(".mp3"); filePicker.FileTypeFilter.Add(".wav"); filePicker.FileTypeFilter.Add(".wma"); filePicker.FileTypeFilter.Add(".m4a"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile file = await filePicker.PickSingleFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file); if (AudioFileNodeCreationStatus.Success != fileInputResult.Status) { // Cannot read input file await ShowMessage(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString())); return; } fileInput = fileInputResult.FileInputNode; fileInput.AddOutgoingConnection(deviceOutput); fileButton.Background = new SolidColorBrush(Colors.Green); // Trim the file: set the start time to 3 seconds from the beginning // fileInput.EndTime can be used to trim from the end of file fileInput.StartTime = TimeSpan.FromSeconds(3); // Enable buttons in UI to start graph, loop and change playback speed factor graphButton.IsEnabled = true; }
/// <summary> /// Loads audio file. /// </summary> /// <param name="PlayPosition"></param> /// <returns></returns> private async Task LoadAudioFile(TimeSpan PlayPosition) { if (soundFile != null) { ClearErrorMessage(); StartButtonEnabled = false; StopButtonEnabled = false; FileName = ""; try { await BuildAudioGraph(); } catch (Exception ex) { ShowErrorMessage(ex.Message); return; } emitter = new AudioNodeEmitter(AudioNodeEmitterShape.CreateOmnidirectional(), AudioNodeEmitterDecayModel.CreateCustom(0.1, 1), AudioNodeEmitterSettings.None); emitter.Position = new Vector3((float)X, (float)Z, (float)-Y); CreateAudioFileInputNodeResult inCreateResult = await graph.CreateFileInputNodeAsync(soundFile, emitter); switch (inCreateResult.Status) { case AudioFileNodeCreationStatus.FormatNotSupported: case AudioFileNodeCreationStatus.InvalidFileType: ShowErrorMessage(String.Format("Could not load {0}. \n\nPlease choose a different file - For Windows Spatial Sound processing, audio files must be Mono 48kHz PCM Wav.", soundFile.Name)); return; case AudioFileNodeCreationStatus.UnknownFailure: case AudioFileNodeCreationStatus.FileNotFound: ShowErrorMessage(String.Format("Audio file load error: {0}", inCreateResult.Status.ToString())); return; } //Dispose of previous input node. if (currentAudioFileInputNode != null) { try { currentAudioFileInputNode.Dispose(); } catch (ObjectDisposedException) { //Do nothing } } currentAudioFileInputNode = inCreateResult.FileInputNode; currentAudioFileInputNode.AddOutgoingConnection(deviceOutput); currentAudioFileInputNode.FileCompleted += CurrentAudioFileInputNode_FileCompleted; FileName = currentAudioFileInputNode.SourceFile.Name; if (PlayPosition != TimeSpan.Zero) { currentAudioFileInputNode.Seek(PlayPosition); graph.Start(); StopButtonEnabled = true; } else { StartButtonEnabled = true; } } }
/// <summary> /// Connect all the nodes together to form the graph, in this case we only have 2 nodes /// </summary> private void ConnectNodes() { _fileInputNode.AddOutgoingConnection(_submixNode); _submixNode.AddOutgoingConnection(_deviceOutputNode); }