private void OnPlayerOutputReady(AudioToolbox.OutputAudioQueue outputAudioQueue) { Console.WriteLine($"Player: Output Ready"); _audioQueueTimeline = outputAudioQueue.CreateTimeline(); MediaStateChanged.Invoke(MediaState.Opened); }
/// <summary> /// Loads the specified file into the player. /// </summary> /// <param name="fileName">Path to the music file.</param> /// <returns>Boolean</returns> public async Task <bool> Load(Mediafile mediaFile) { if (mediaFile != null && mediaFile.Length != "00:00") { try { string path = mediaFile.Path; await InitializeCore.Dispatcher.RunAsync(() => { MediaChanging?.Invoke(this, new EventArgs()); }); await Stop(); await Task.Run(() => { _handle = Bass.CreateStream(path, 0, 0, BassFlags.AutoFree | BassFlags.Float); PlayerState = PlayerState.Stopped; Length = 0; Length = Bass.ChannelBytes2Seconds(_handle, Bass.ChannelGetLength(_handle)); Bass.FloatingPointDSP = true; Bass.ChannelSetDevice(_handle, 1); Bass.ChannelSetSync(_handle, SyncFlags.End | SyncFlags.Mixtime, 0, _sync); Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 5), _posSync); Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 15), _posSync); CurrentlyPlayingFile = mediaFile; }); if (Equalizer == null) { Equalizer = new BassEqualizer(_handle); } else { (Equalizer as BassEqualizer).ReInit(_handle); } MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped)); return(true); } catch (Exception ex) { await InitializeCore.NotificationManager.ShowMessageAsync(ex.Message + "||" + mediaFile.OrginalFilename); } } else { string error = "The file " + mediaFile?.OrginalFilename + " is either corrupt, incomplete or unavailable. \r\n\r\n Exception details: No data available."; if (IgnoreErrors) { await InitializeCore.NotificationManager.ShowMessageAsync(error); } else { await InitializeCore.NotificationManager.ShowMessageBoxAsync(error, "File corrupt"); } } return(false); }
private async Task StreamDownloadHandler(Guid guid, CancellationToken cancellationToken) { var buffer = new byte[8192]; long totalNumberBytesRead = 0; _totalStreamLength = 0L; _audioQueueTimeline = null; Console.WriteLine($"Downloader started"); try { using (_player = new StreamingPlayback()) { _player.OutputReady += OnPlayerOutputReady; _player.Finished += OnPlayerFinished; _player.AudioPlayerStateChanged += OnAudioPlayerStateChanged; Uri requestUri = GetRequestUri(guid); using (var httpClient = await _requestService.GetHttpClient()) { using (var response = await TryGetAsync(0, requestUri, httpClient, cancellationToken)) { _totalStreamLength = response.Content.Headers.ContentLength.GetValueOrDefault(totalNumberBytesRead); Console.WriteLine($"Stream Length: {_totalStreamLength}"); using (var inputStream = await GetQueueStream(response.Content, cancellationToken)) { //var inputStream = await response.Content.ReadAsStreamAsync(); int inputStreamLength; while (((inputStreamLength = inputStream.Read(buffer, 0, buffer.Length)) != 0) || !cancellationToken.IsCancellationRequested) { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } //Console.WriteLine($"{nameof(StreamDownloadHandler)} read {totalNumberBytesRead} from {_totalStreamLength} "); totalNumberBytesRead += inputStreamLength; _player.ParseBytes(buffer, inputStreamLength, false, totalNumberBytesRead == (int)_totalStreamLength); } } } } } } catch (HttpStatusRequestException exception) { Console.WriteLine($"Exception thrown in {nameof(StreamDownloadHandler)} with message {exception.Message}"); if (exception.StatusCode == System.Net.HttpStatusCode.BadRequest) { MediaStateChanged.Invoke(MediaState.BadRequest); } } catch (Exception exception) { Console.WriteLine($"Exception thrown in {nameof(StreamDownloadHandler)} with message {exception.Message}"); } }
internal void PostMediaStateChangedEvent(MediaPlaybackState oldValue, MediaPlaybackState newValue) { LogEventStart(nameof(MediaStateChanged)); Library.GuiContext.EnqueueInvoke(() => { MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(oldValue, newValue)); LogEventDone(nameof(MediaStateChanged)); }); }
/// <summary> /// Pauses the audio playback. /// </summary> /// <returns></returns> public async Task Pause() { PlayerState = PlayerState.Paused; MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Paused)); await Task.Run(async() => { Bass.ChannelSlideAttribute(_handle, ChannelAttribute.Volume, 0, 500); await Task.Delay(500); Bass.ChannelPause(_handle); //var vol = (float)Volume / 100f; //Bass.ChannelSetAttribute(handle, ChannelAttribute.Volume, vol); }); }
/// <summary> /// Starts the audio playback. /// </summary> /// <returns></returns> public async Task Play() { await Task.Run(() => { Bass.ChannelSetAttribute(_handle, ChannelAttribute.Volume, 0f); Bass.ChannelPlay(_handle); var vol = (float)Volume / 100f; Bass.ChannelSlideAttribute(_handle, ChannelAttribute.Volume, vol, 1000); PlayerState = PlayerState.Playing; }); MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Playing)); }
/// <summary> /// Called when [media state changed]. /// </summary> internal void OnMediaStateChanged() { if (MediaState != MediaState.Error) { ErrorMessage = string.Empty; } MediaStateChanged?.Invoke(this, new MediaProgressEventArgs { State = MediaState }); UdpdateCommands(); }
public Task Stop() { MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped)); return(Task.Run(() => { _fmodChannel?.Stop(); _fmodSound?.Release(); Length = 0; Position = -1; CurrentlyPlayingFile = null; PlayerState = PlayerState.Stopped; })); }
/// <summary> /// Loads the specified file into the player. /// </summary> /// <returns>Boolean</returns> private async Task <bool> LoadMusicAsync(Action LoadMusicAction) { try { await InitializeSwitch.Dispatcher.RunAsync(() => { MediaChanging?.Invoke(this, new EventArgs()); }); await Stop(); await Task.Run(() => { PlayerState = PlayerState.Stopped; LoadMusicAction(); //loads the respective stream if (Length <= 1) { Length = Bass.ChannelBytes2Seconds(_handle, Bass.ChannelGetLength(_handle)); } IsSeekable = Bass.ChannelGetLength(_handle) != -1; Bass.FloatingPointDSP = true; Bass.ChannelSetDevice(_handle, 1); Bass.ChannelSetSync(_handle, SyncFlags.End | SyncFlags.Mixtime, 0, _sync); Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 5), _posSync); Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 15), _posSync); }); if (InitializeSwitch.IsMobile) { await ChangeDevice(); } if (Equalizer == null) { Equalizer = new BassEqualizer(_handle); } else { (Equalizer as BassEqualizer).ReInit(_handle); } MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped)); return(true); } catch (Exception ex) { BLogger.E("An error occured while loading music. Action {action}", ex, LoadMusicAction.ToString()); await InitializeSwitch.NotificationManager.ShowMessageAsync(ex.Message); return(false); } }
/// <summary> /// Stops the playback if it is playing. /// </summary> /// <returns></returns> public async Task Stop() { await Task.Run(() => { Length = 0; Position = -1; Bass.StreamFree(_handle); Bass.ChannelStop(_handle); // Stop Playback. Bass.MusicFree(_handle); _handle = 0; CurrentlyPlayingFile = null; PlayerState = PlayerState.Stopped; }); MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped)); }
private void OnMessageReceived(object sender, Common.MessageReceivedEventArgs <Messaging.Session.SessionMessageBase> e) { switch (e.Message) { case MediaStateMessage msg_state: //System.Diagnostics.Debug.WriteLine($"Got a media state message: {Newtonsoft.Json.JsonConvert.SerializeObject(msg_state)}"); CurrentMediaState = msg_state.State; MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(msg_state.State)); break; case MediaControllerRemovedMessage msg_removed: CurrentMediaState = null; MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(null)); break; } }
public Task Play() { MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Playing)); return(Task.Run(() => { //set paused to false _fmodChannel.SetPaused(false); //update volume. Volume = Volume; //set fade points to first 3 seconds of the track. //we simply slide the volume from 0 to the default value //in the next 1 second. _fmodChannel.SetFadePoint(0f, _fmodChannel.Volume, _fmodSound.ConvertSecondsToPcm(1)); PlayerState = PlayerState.Playing; })); }
public Task Pause() { MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Paused)); return(Task.Run(async() => { //set state to paused before we pause //this is to update the UI quickly. PlayerState = PlayerState.Paused; //set fade points to first 3 seconds of the track. //we simply slide the volume from default value to 0 in the next 0.5 second. _fmodChannel.SetFadePoint(_fmodChannel.Volume, 0f, _fmodSound.ConvertSecondsToPcm(0.5)); //wait for the fade to over. await Task.Delay(500); //set paused to true _fmodChannel.SetPaused(true); })); }
protected virtual void OnMediaStateChanged(EventArgs e) { MediaStateChanged?.Invoke(this, e); }
/// <summary> /// MediaPlayer state changed event handlers. /// Note that we can subscribe to events even if Media Player is playing media in background /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void MediaPlayer_CurrentStateChanged(MediaPlayer sender, object args) { CurrentState = sender.CurrentState; await _dispatcherUtility.RunAsync(() => { MediaStateChanged?.Invoke(sender, CurrentState); }); }
public DesignPlayerService() { MediaStateChanged?.Invoke(this, MediaPlayerState.Playing); TrackChanged?.Invoke(this, "test"); }
private void OnPlayerFinished(object sender, EventArgs e) { Console.WriteLine($"Player: Output Finished"); MediaStateChanged.Invoke(MediaState.Ended); }
/// <summary> /// Loads the specified file into the player. /// </summary> /// <returns>Boolean</returns> private async Task <bool> LoadMusicAsync(Action LoadMusicAction) { try { await InitializeSwitch.Dispatcher.RunAsync(() => { MediaChanging?.Invoke(this, new EventArgs()); }); await Stop(); Result loadResult = Result.Ok; await Task.Run(() => { PlayerState = PlayerState.Stopped; LoadMusicAction(); //loads the respective stream //load the stream into the channel but don't play it yet. loadResult = _fmodSys.PlaySound(_fmodSound, null, true, out _fmodChannel); }); //get and update length of the track. Length = TimeSpan.FromMilliseconds(_fmodSound.LengthInMilliseconds).TotalSeconds; //set the channel callback for all the syncpoints loadResult = _fmodChannel.SetCallback(_channelEndCallback); //add all the sync points //1. when song ends loadResult = _fmodSound.AddSyncPoint(_fmodSound.LengthInMilliseconds, TimeUnit.Ms, "songended", out _endSyncPoint); //2. when song has reached the last 15 seconds loadResult = _fmodSound.AddSyncPoint(_fmodSound.LengthInMilliseconds - 15000, TimeUnit.Ms, "songabouttoended", out _last15SyncPoint); //3. when song has reached the last 5 seconds loadResult = _fmodSound.AddSyncPoint(_fmodSound.LengthInMilliseconds - 5000, TimeUnit.Ms, "fade", out _last5SyncPoint); //update the system once here so that //all the sync points and callbacks are saved and updated. loadResult = _fmodSys.Update(); await InitializeSwitch.Dispatcher.RunAsync(() => { if (Equalizer == null) { Equalizer = new FmodEqualizer(_fmodSys, _fmodChannel); } else { (Equalizer as FmodEqualizer).ReInit(_fmodSys, _fmodChannel); } MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped)); }); return(true); } catch (Exception ex) { BLogger.E("An error occured while loading music. Action {action}", ex, LoadMusicAction.ToString()); await InitializeSwitch.NotificationManager.ShowMessageAsync(ex.Message); return(false); } }