Peter Daukintis
Some changes occurred in the consumer preview release of Windows 8 regarding background audio; the steps required to get it working are outlined in this forum post
The steps are
- Create a MediaElement and set it’s AudioCategory property to ‘BackgroundCapableMedia’
<MediaElement x:Name="myMedia"
Source="/Assets/Sleep Away.mp3"
AudioCategory="BackgroundCapableMedia"/> - Update the app manifest to declare Background Tasks of types ‘Audio’ and ‘Control Channel’
- Implement event handlers for
- MediaControl.PlayPressed
- MediaControl.PausePressed
- MediaControl.PlayPauseTogglePressed
- MediaControl.StopPressed
{
this.InitializeComponent();
MediaControl.PlayPressed += MediaControl_PlayPressed;
MediaControl.PausePressed += MediaControl_PausePressed;
MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
MediaControl.StopPressed += MediaControl_StopPressed;
}
private void MediaControl_StopPressed(object sender, object e)
{
myMedia.Stop();
}
private void MediaControl_PlayPauseTogglePressed(object sender, object e)
{
}
private void MediaControl_PausePressed(object sender, object e)
{
myMedia.Pause();
}
private void MediaControl_PlayPressed(object sender, object e)
{
myMedia.Play();
}
The media transport event handlers which need to be implemented are detailed here http://msdn.microsoft.com/en-us/library/windows/hardware/hh833781.aspx
Here’s a working sample project.
UPDATE: I have updated this for the Release Preview (see http://babaandthepigman.wordpress.com/2012/08/12/metro-background-audio-c-release-preview/)
Hi, I downloaded your sample project but found the “pause” button didn’t work when I press the volume button. Also, I followed the steps you described and ran into the same problem. confused…
Probably because it’s hitting this MediaControl_PlayPauseTogglePressed handler which has no code in it? That was the case for me so I simply put toggling code in there based on the Status.
hi, Can you share which code you added for toggling. I am trying to mymedia inside that event and it is giving me UI Thread Error.
@tarun, yes you will get that problem, the event doesn’t come from the UI thread.
You need to schedule it on the dispatcher….
private void MediaControl_PlayPauseTogglePressed(object sender, object e)
{
Dispatcher.InvokeAsync(CoreDispatcherPriority.High, (s, args) =>
{
if (CurrentState != MediaElementState.Playing)
{
Play();
}
else
{
Pause();
}
},
this, null);
}
Hi,
Unfortunately, this sample does not work for the Release Preview. I have built a sample using the same settings in RP but the media pauses working when you navigate to another app i.e. does not play in background. Any ideas?
hi steve,
I’ve now updated the project to work with the RP – see http://t.co/TOcdMYgI
Outstanding post however I was wondering if you could write a litte more on
this subject? I’d be very grateful if you could elaborate a little bit more. Thank you!