private void PlayPauseMusic(object sender, EventArgs eventArgs) { //If the mediaPlayer previously played before. if (mediaPlayer != null) { //If a current music is playing if (mediaPlayer.IsPlaying) { //If the currently playing song does not match the displayed song. if (currentPlayingSong != displayedSong) { //plays the new song. playBtn.SetImageDrawable(GetDrawable(Resource.Drawable.pause)); PreparePlayer(true); } else { //Otherwise, pause the music. mediaPlayer.Pause(); playBtn.SetImageDrawable(GetDrawable(Resource.Drawable.play)); } } else { //else plays the music. playBtn.SetImageDrawable(GetDrawable(Resource.Drawable.pause)); //If the music was previously in a paused state. if (mediaPlayer.CurrentPosition != 0 && currentPlayingSong == displayedSong) { mediaPlayer.Start(); headerTitle.Text = "Now playing~ " + Utils.Truncate(currentPlayingSong.GetSongTitle(), 5) + ".."; } else { PreparePlayer(true); } } } else { //Called mainly once (When app launches and first time playing.) PreparePlayer(true); playBtn.SetImageDrawable(GetDrawable(Resource.Drawable.pause)); } }
private void PreparePlayer(bool playMusic = false) { try { //Clears the current seekbar thread first if its running. if (musicThread.IsAlive) { ThreadHandler(1); } //Flushs the mediaplayer. if (mediaPlayer != null) { //If the player is playing. if (mediaPlayer.IsPlaying) { //Stops the player first. mediaPlayer.Stop(); } mediaPlayer.Reset(); mediaPlayer.Release(); } //Set the mediaplayer source. mediaPlayer = new MediaPlayer(); mediaPlayer.SetDataSource(displayedSong.GetFileDirectory().Path); mediaPlayer.Prepare(); if (playMusic) { mediaPlayer.Start(); currentPlayingSong = displayedSong; Utils.ShowToast(this, "Now playing: " + displayedSong.GetSongTitle()); headerTitle.Text = "Now playing~ " + Utils.Truncate(currentPlayingSong.GetSongTitle(), 5) + ".."; mediaPlayer.Completion += MediaPlayerOnCompletion; ThreadHandler(0); } } catch (Exception p) { //For debug purpose. Utils.ShowToast(this, "ERROR: " + p.Message, false, ToastLength.Long); } }