AudioPlayerAgent Streaming - Stop doesnt delete the buffer - c#

I'm currently developing a web radio app and if the user presses the pause/stop key the stream should stop and of course when he presses play again the stream should continue.
The problem I have is, that player.Stop() only pauses the track. If you press continue again, the first 5 secounds are not read from the stream but from a buffer, then it playes no sound for a few secounds and then begins to read from the stream again.
This is fatal for a web radio app. How can I fix it? Or how can I delete the buffer?
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
switch (playState)
{
case PlayState.TrackReady:
player.Play();
break;
case PlayState.Stopped:
player.Stop();
break;
case PlayState.Paused:
player.Stop();
break;
}
NotifyComplete();
}

Allright.. just to let you guys know, this is what I did. I don't know if there's any better way but this works for me:
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
switch (playState)
{
case PlayState.Stopped:
track.BeginEdit();
track.Tag = track.Source.OriginalString;
track.Source = new Uri("http://127.0.0.1", UriKind.Absolute);
track.EndEdit();
player.Track = track;
break;
protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param)
{
switch (action)
{
case UserAction.Play:
if (player.PlayerState != PlayState.Playing)
{
try
{
player.Play();
}
catch(Exception)
{
track.BeginEdit();
track.Source = new Uri(player.Track.Tag, UriKind.Absolute);
track.EndEdit();
player.Track = track;
player.Play();
}
}
break;
case UserAction.Stop:
case UserAction.Pause:
if (player.Track.Source.OriginalString != "http://127.0.0.1/")
{
player.Stop();
}
break;

How about ditching everything when you stop, and newing it up again when playback starts again? It seems the functionality you are using is more suited to pausing static content. Pause doesn't make much sense with radio.

Related

Xamarin. Having trouble correctly implementing AudioManager AudioFocus activity and listeners

I have a media podcast app built with xamarin forms and I am attempting to implement MediaManager's AudioFocus so my app can play well with other media apps. My main issue is being able to call RequestAudioFocus() when the user first clicks play and then also get the listener to work if another app starts playing media while my app is in the background. So both audios are not playing at the same time.
If I stick this code in MainActivity then the request works fine but also I don't really want the request to happen when the user opens the app. I want it to happen when the user clicks play.
I built a notification a while back that pops up a notification when the user first loads an episode that has a play/pause button in there as well that starts an activity to play/pause the episode. If I stick this code in that activity then everything works pretty well, even the listener in regard to other apps interfering. But again, I don't want to request audio focus only when they click the notification outside the app, I want it to start when they also click the play button inside the app.
So now I've built out another activity (different than the notification one). But I don't completely understand yet how to call this activity. If someone could point me in the right direction that would be great. I've been researching docs and other tutorials but I could use a nudge in the right direction. Thanks for your time.
One of the resources I am using can be found at https://www.sitepoint.com/managing-multiple-sound-sources-in-android-with-audio-focus/
This returns false every time. Doesn't get past the initialization of AudioManager.
public bool RequestAudioFocus()
{
AudioManager audioManager = (AudioManager)GetSystemService(AudioService);
AudioFocusRequest audioFocusRequest;
if (Build.VERSION.SdkInt > BuildVersionCodes.O)
{
audioFocusRequest = audioManager.RequestAudioFocus(new AudioFocusRequestClass.Builder(AudioFocus.Gain)
.SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Android.Media.Stream.Music).Build()).SetOnAudioFocusChangeListener(this)
.Build());
}
else
{
audioFocusRequest = audioManager.RequestAudioFocus(this, Android.Media.Stream.Music, AudioFocus.Gain);
}
if (audioFocusRequest == AudioFocusRequest.Granted)
{
return true;
}
return false;
}
public void Init(DabPlayer Player, bool IntegrateWithLockScreen)
{
dabplayer = Player;
var mSession = new MediaSessionCompat(Application.Context, "MusicService");
mSession.SetFlags(MediaSessionCompat.FlagHandlesMediaButtons | MediaSessionCompat.FlagHandlesTransportControls);
var controller = mSession.Controller;
var description = GlobalResources.playerPodcast;
if (IntegrateWithLockScreen)
{
/* SET UP LOCK SCREEN */
CreateNotificationChannel();
dabplayer.EpisodeDataChanged += (sender, e) =>
{
bool focus = RequestAudioFocus();
if (focus)
{
// Set up an intent so that tapping the notifications returns to this app:
Intent intent = new Intent(Application.Context, typeof(MainActivity));
Intent playPauseIntent = new Intent(Application.Context, typeof(SecondActivity));
//Intent audioFocusIntent = new Intent(Application.Context, typeof(AudioFocusActivity));
// Create a PendingIntent;
const int pendingIntentId = 0;
const int firstPendingIntentId = 1;
//const int audioFocusIntentId = 2;
//PendingIntent audioFocusPendingIntent =
// PendingIntent.GetActivity(Application.Context, audioFocusIntentId, audioFocusIntent, 0);
PendingIntent firstPendingIntent =
PendingIntent.GetActivity(Application.Context, firstPendingIntentId, intent, 0);
PendingIntent pendingIntent =
PendingIntent.GetActivity(Application.Context, pendingIntentId, playPauseIntent, 0);
// Build the notification:
var builder = new NotificationCompat.Builder(Application.Context, CHANNEL_ID)
.SetStyle(new Android.Support.V4.Media.App.NotificationCompat.MediaStyle()
.SetMediaSession(mSession.SessionToken)
.SetShowActionsInCompactView(0))
.SetVisibility(NotificationCompat.VisibilityPublic)
.SetContentIntent(firstPendingIntent) // Start up this activity when the user clicks the intent.
.SetDeleteIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(Application.Context, PlaybackState.ActionStop))
.SetSmallIcon(Resource.Drawable.app_icon) // This is the icon to display
.AddAction(Resource.Drawable.ic_media_play_pause, "Play", pendingIntent)
.SetContentText(GlobalResources.playerPodcast.EpisodeTitle)
.SetContentTitle(GlobalResources.playerPodcast.ChannelTitle);
// Finally, publish the notification:
var notificationManager = NotificationManagerCompat.From(Application.Context);
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
//StartActivity(audioFocusIntent); causes trying to invoke virtual method on
//null object reference when code and code above is uncommented
}
};
dabplayer.EpisodeProgressChanged += (object sender, EventArgs e) =>
{
};
}
}
This is the activity that was originally just supposed to be used for the notification area
[Activity]
public class SecondActivity : Activity, AudioManager.IOnAudioFocusChangeListener
{
DabPlayer player = GlobalResources.playerPodcast;
EpisodeViewModel Episode;
public bool RequestAudioFocus()
{
AudioManager audioManager = (AudioManager)GetSystemService(AudioService);
AudioFocusRequest audioFocusRequest;
if (Build.VERSION.SdkInt > BuildVersionCodes.O)
{
audioFocusRequest = audioManager.RequestAudioFocus(new AudioFocusRequestClass.Builder(AudioFocus.Gain)
.SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Android.Media.Stream.Music).Build()).SetOnAudioFocusChangeListener(this)
.Build());
}
else
{
audioFocusRequest = audioManager.RequestAudioFocus(this, Android.Media.Stream.Music, AudioFocus.Gain);
}
if (audioFocusRequest == AudioFocusRequest.Granted)
{
return true;
}
return false;
}
public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
{
switch (focusChange)
{
case AudioFocus.Gain:
player.Play();
//Gain when other Music Player app releases the audio service
break;
case AudioFocus.Loss:
//We have lost focus stop!
player.Stop();
break;
case AudioFocus.LossTransient:
//We have lost focus for a short time, but likely to resume so pause
player.Pause();
break;
case AudioFocus.LossTransientCanDuck:
//We have lost focus but should till play at a muted 10% volume
//player.SetVolume(.1);
break;
}
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
if (player.IsReady)
{
if (player.IsPlaying)
{
player.Pause();
}
else
{
if (RequestAudioFocus())
{
player.Play();
}
}
}
else
{
if (player.Load(Episode.Episode))
{
if (RequestAudioFocus())
{
player.Play();
}
}
else
{
//DisplayAlert("Episode Unavailable", "The episode you are attempting to play is currently unavailable. Please try again later.", "OK");
}
}
Finish();
}
}
This is the new activity I built and hoping to use when the user interacts with the player but I'm not sure how to call/implement it.
[Activity]
public class AudioFocusActivity : Activity, AudioManager.IOnAudioFocusChangeListener
{
DabPlayer player = GlobalResources.playerPodcast;
DroidDabNativePlayer droid = new DroidDabNativePlayer();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestAudioFocus();
}
public bool RequestAudioFocus()
{
AudioManager audioManager = (AudioManager)GetSystemService(AudioService);
AudioFocusRequest audioFocusRequest;
if (Build.VERSION.SdkInt > BuildVersionCodes.O)
{
audioFocusRequest = audioManager.RequestAudioFocus(new AudioFocusRequestClass.Builder(AudioFocus.Gain)
.SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Android.Media.Stream.Music).Build()).SetOnAudioFocusChangeListener(this)
.Build());
}
else
{
audioFocusRequest = audioManager.RequestAudioFocus(this, Android.Media.Stream.Music, AudioFocus.Gain);
}
if (audioFocusRequest == AudioFocusRequest.Granted)
{
return true;
}
return false;
}
public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
{
switch (focusChange)
{
case AudioFocus.Gain:
player.Play();
//Gain when other Music Player app releases the audio service
break;
case AudioFocus.Loss:
//We have lost focus stop!
player.Stop();
break;
case AudioFocus.LossTransient:
//We have lost focus for a short time, but likely to resume so pause
player.Pause();
break;
case AudioFocus.LossTransientCanDuck:
//We have lost focus but should till play at a muted 10% volume
//player.SetVolume(.1);
break;
}
}
}
This is just my play method in my androidplayer class
/// Begin playback or resume if paused
public void Play()
{
if (player == null)
return;
if (IsPlaying)
{
//Go back to the beginning (don't start playing)... not sure what this is here for if if it ever gets hit.
Pause();
Seek(0);
}
else if (player.CurrentPosition >= player.Duration)
{
//Start over from the beginning if at the end of the file
player.Pause();
Seek(0);
}
else
{
//Play from where we're at
}
player.Start();
}
If I were you I would put both your Audio Focus code and your Audio Player code in a ForegroundService and not the Activity, this way you can navigate to different activities, without interrupting Audio Playback. You will need to do something like that anyways if you want playback when the App is in the background.
Implementing a ForegroundService will also let you add buttons to your notification or if you are using one of the rich Audio Notification, then you can send intents directly to your ForegroundService from the buttons on the notification, rather than having to open up your App. So for your pending intents you could communicate directly with the service instead.
Also when requesting audio focus, you need to respect whether the audio focus was granted or not. Right now you are just requesting it and throwing away the result. Only if the focus was granted you should start playing back the audio.

Android: Sending Metadata from media player app to car stereo via bluetooth blocks broadcast receiver to play next song or pause music

I am working on a little media player app. When I go into my car, I want the app to play music and show the current song's metadata on my car stereo's screen. But I also want the media player to play the NEXT song, when I press NEXT on my car stereo.
I got both function to work already, but not together.
Sounds a bit wierd but let me explain:
First, I set up a broadcast receiver in my app to catch the next, prev, paus, and stop clicks from a remote bluetooth device, such as a car stereo ( or a headset, etc). This looks like this:
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionMediaButton })]
public class MyMediaButtonBroadcastReceiver : BroadcastReceiver
{
public string ComponentName { get { return Class.Name; } }
static long lastClick = 0;
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action != Intent.ActionMediaButton)
return;
var keyEvent = (KeyEvent)intent.GetParcelableExtra(Intent.ExtraKeyEvent);
switch (keyEvent.KeyCode)
{
case Keycode.Headsethook:
if(canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaPlay:
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaPlayPause:
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaNext:
if(Activity_Player.CurrentSongObject != null && canClick())
Activity_Player.Instance.ChooseRandomNewSongAndPlay(false);
break;
case Keycode.MediaPrevious:
if (Activity_Player.CurrentSongObject != null && canClick())
Activity_Player.mediaPlayer.SeekTo(0);
break;
}
if (intent.GetStringExtra(BluetoothAdapter.ExtraState) == BluetoothAdapter.ActionConnectionStateChanged)
{
Toast.MakeText(Activity_Player.ctx, "connection off1", ToastLength.Short).Show();
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
}
}
private bool canClick()
{
if(lastClick < Java.Lang.JavaSystem.CurrentTimeMillis() - 500) // needs to be atleast one second bigger
{
lastClick = Java.Lang.JavaSystem.CurrentTimeMillis();
return true;
}
else
return false;
}
}
I Init this broadcast receiver in my app like so:
private void RegisterBroadCastReceiver()
{
var am = (AudioManager)this.GetSystemService(AudioService);
var componentName = new ComponentName(PackageName, new MyMediaButtonBroadcastReceiver().ComponentName);
am.RegisterMediaButtonEventReceiver(componentName);
}
Again: this totally worked perfectly.
But then I noticed that my car stereo does not display the current song information (meta data from the mp3) on its screen. So with a bit of googeling I coded this:
private void InitBluetoohSending()
{
if (mAudioManager == null)
{
mAudioManager = (AudioManager)GetSystemService(Context.AudioService);
}
if (Build.VERSION.SdkInt < Build.VERSION_CODES.Lollipop)
{
if (mRemoteControlClient == null)
{
mRemoteControlClient = new RemoteControlClient(PendingIntent.GetBroadcast(this, 0, new Intent(Intent.ActionMediaButton), 0));
mAudioManager.RegisterRemoteControlClient(mRemoteControlClient);
}
}
else
{
if (mMediaSession == null)
{
mMediaSession = new MediaSession(this, "PlayerServiceMediaSession");
mMediaSession.SetFlags(MediaSession.FlagHandlesTransportControls);
mMediaSession.Active = true;
}
}
}
AND:
public static void SendInfoToBluetoothDevice()
{
if (Build.VERSION.SdkInt < Build.VERSION_CODES.Lollipop)
{
RemoteControlClient.MetadataEditor ed = mRemoteControlClient.EditMetadata(true);
ed.PutString(MediaMetadataRetriever.MetadataKeyTitle, CurrentSongObject.SongName);
ed.PutString(MediaMetadataRetriever.MetadataKeyArtist, CurrentSongObject.ArtistName);
ed.PutString(MediaMetadataRetriever.MetadataKeyAlbum, CurrentSongObject.AlbumName);
ed.PutLong(MediaMetadataRetriever.MetadataKeyDuration, CurrentSongObject.DurationInSec);
ed.Apply();
mRemoteControlClient.SetPlaybackState(RemoteControlClient.PlaystatePlaying, mediaPlayer.CurrentPosition, 1.0f);
}
else
{
MediaMetadata metadata = new MediaMetadata.Builder()
.PutString(MediaMetadata.MetadataKeyTitle, CurrentSongObject.SongName)
.PutString(MediaMetadata.MetadataKeyArtist, CurrentSongObject.ArtistName)
.PutString(MediaMetadata.MetadataKeyAlbum, CurrentSongObject.AlbumName)
.PutLong(MediaMetadata.MetadataKeyDuration, CurrentSongObject.DurationInSec)
.Build();
mMediaSession.SetMetadata(metadata);
PlaybackState state = new PlaybackState.Builder()
.SetActions(PlaybackState.ActionPlay)
.SetState(PlaybackState.StatePlaying, mediaPlayer.CurrentPosition, 1.0f, SystemClock.ElapsedRealtime())
.Build();
mMediaSession.SetPlaybackState(state);
}
}
Again, this works fine. I am calling the last function everytime I change the track on my phone and the car stereo displays everything as it should BUT now the broadcast receiver to catch the next, pause, prev, and play clicks from the car stopped working immediately.
They do however still work, when the phone is NOT sending out the info. Before sending info out, I am checking wether a device is connected or not like so:
if (mAudioManager.BluetoothA2dpOn)
{
SendInfoToBluetoothDevice();
}
With my headset on but no device connected, I can stop my music with the headset just fine. As soon as I am in my car and the car stereo now displays the songs (a device is now connected) I cannot use my headset hook anymore, neither my next or prev buttons on my car ...
This is especially frustrating since I have to try some code and then go back to my car with a release version on my phone to see if anything worked, but with no debugger attached. Also, I dont know what to change since both things work just fine individually but stop working once used together. Or at least the receiver stops working entirely when the sender is active.
Please, can anyone help me out here?
Thanks a lot!
Thank god, I have found it!
The problem was the mediaSession. This itself registered a broadcast receiver which interefered with my custom one. The issue was very simple:
First, remove the "old" broadcast receiver entirely, then go:
mMediaSession = new MediaSession(this, "PlayerServiceMediaSession");
mMediaSession.SetFlags(MediaSession.FlagHandlesTransportControls);
mMediaSession.SetFlags(MediaSession.FlagHandlesMediaButtons);
mMediaSession.Active = true;
mMediaSession.SetCallback(new MediaButtonReceiver(this));
And for the custom class:
public class MediaButtonReceiver : MediaSession.Callback
{
static long lastClick = 0;
Context ctx;
public MediaButtonReceiver(Context ctx)
{
this.ctx = ctx;
}
public override bool OnMediaButtonEvent(Intent mediaButtonIntent)
{
if (mediaButtonIntent.Action != Intent.ActionMediaButton)
return false;
var keyEvent = (KeyEvent)mediaButtonIntent.GetParcelableExtra(Intent.ExtraKeyEvent);
switch (keyEvent.KeyCode)
{
case Keycode.Headsethook:
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaPlay:
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaPlayPause:
if (canClick())
Activity_Player.Instance.PlayOrPauseLogic();
break;
case Keycode.MediaNext:
if (Activity_Player.CurrentSongObject != null && canClick())
Activity_Player.Instance.ChooseRandomNewSongAndPlay(false);
break;
case Keycode.MediaPrevious:
if (Activity_Player.CurrentSongObject != null && canClick())
Activity_Player.mediaPlayer.SeekTo(0);
break;
}
return base.OnMediaButtonEvent(mediaButtonIntent);
}
private bool canClick()
{
if (lastClick < Java.Lang.JavaSystem.CurrentTimeMillis() - 500) // needs to be atleast one second bigger
{
lastClick = Java.Lang.JavaSystem.CurrentTimeMillis();
return true;
}
else
return false;
}
}

What's the easiest way to play audio in background in UWP?

I am working on my Project (a soundcloud client) and the app can play tracks just fine, but not when the app is minimized. I use the MediaElement-Object for playing the mp3 from the url. How can i force the music to continue playing the music, when the app is in the background. Or whats the easiest way/best explained tutorial to implement this. I searched alot for a good answer, but the ones, i found, was too good for me :D What means, that i didn't understand it.
To play audio in the background you will have to do a Declaration in Package.appxmanifest for a Background Tasks, enable audio and add an entry point like TestUWP.MainPage page.
Also for the user to easily be able to manage the audio you can use SystemMediaTransportControls
Here is a basic setup with Play and Pause.
xaml
<MediaElement x:Name="mediaElement" Height="100" Width="100" AreTransportControlsEnabled="True"/>
C#
public MainPage()
{
this.InitializeComponent();
systemControls = SystemMediaTransportControls.GetForCurrentView();
// Register to handle the following system transpot control buttons.
systemControls.ButtonPressed += SystemControls_ButtonPressed;
mediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
}
private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (mediaElement.CurrentState)
{
case MediaElementState.Playing:
systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Paused:
systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Stopped:
systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
case MediaElementState.Closed:
systemControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
default:
break;
}
}
void SystemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
PlayMedia();
break;
case SystemMediaTransportControlsButton.Pause:
PauseMedia();
break;
case SystemMediaTransportControlsButton.Stop:
StopMedia();
break;
default:
break;
}
}
private async void StopMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
mediaElement.Stop();
});
}
async void PlayMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (mediaElement.CurrentState == MediaElementState.Playing)
mediaElement.Pause();
else
mediaElement.Play();
});
}
async void PauseMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
mediaElement.Pause();
});
}
Output
If you like to enable more controls you can do using the available properties for ex.
systemControls.IsNextEnabled = true;
and you have to add the case in the button switch.
case SystemMediaTransportControlsButton.Next:
//handle next song
break;

an error while trying to play an audio in Audio Playback Agent. System.SystemException: HRESULT = 0xC00D001A

I want to play an audio in background.
So I did this iniside my main project
BackgroundAudioPlayer.Instance.Track = audioTrack;
BackgroundAudioPlayer.Instance.Play();
and inside audio background agent:
protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param)
{
switch (action)
{
case UserAction.Play:
player.Play();
break;
case UserAction.Stop:
player.Stop();
break;
case UserAction.Pause:
player.Pause();
break;
case UserAction.FastForward:
player.FastForward();
break;
case UserAction.Rewind:
player.Rewind();
break;
default:
break;
}
NotifyComplete();
}
but I get an error:
System.SystemException: HRESULT = 0xC00D001A
I have another question too: will this continue playing after I close the app?
The error code should say it all:
0xC00D001A
NS_E_FILE_NOT_FOUND
"The system cannot find the file specified."

Pause/Play MP3 file in C# using WMP

I am once again a bit stuck in my practising.
I want an MP3 file to play when i open my program - I can do that, i got music.
I also want a checkbox which allows to pause the music - But either I'm very tired, or the thing won't work - Nothing happens when i check/uncheck it. I've done it like this:
public void PlayPause(int Status)
{
WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
switch (Status)
{
case 0:
wmp.URL = "Musik.mp3";
break;
case 1:
wmp.controls.play();
break;
case 2:
wmp.controls.pause();
break;
}
}
Upon opening the program, the method is called with case 0. Music plays. All good.
However this doesn't work, and i don't get why, as it is pretty simple code.
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
PlayPause(2);
}
else if (checkBox1.Checked == false)
{
PlayPause(1);
}
}
Any idea as to why checking the checkbox doesn't pause/unpause the music?
You're instantiating a completely new WindowsMediaPlayer object each time you call that PlayPause function.
Thus, when you call pause later on, you're pausing nothing.
You need to hold or pass a reference to that WMP object around, so that you're operating on the same one.
Well it's because you are creating a new media player every time you call PlayPause. Create it in the constructor and it should be fine.

Categories