WP7 Silverlight Gotcha: Setting the Source on a MediaElement will stop background music playback
Applies To: Silverlight (the restriction applies to XNA, but the MediaElement
is only Silverlight)
Quick Bits
Simply setting the Source
of a MediaElement
to a valid source will stop any current background playback, causing you to fail Marketplace certification, according to section 6.5.1 from the certification guide.
The Fine Print
From the certification guide:
6.5.1 Initial Launch Functionality
When the user is already playing music on the phone when the application is launched, the application must not pause, resume, or stop the active music in the phone MediaQueue by calling the Microsoft.Xna.Framework.Media.MediaPlayer class. If the application plays its own background music or adjusts background music volume, it must ask the user for consent to stop playing/adjust the background music (e.g. message dialog or settings menu).
Note: This requirement does not apply to applications that play sound effects through the Microsoft.Xna.Framework.Audio.SoundEffect class, as sound effects will be mixed with the MediaPlayer. The SoundEffect class should not be used to play background music.
Note: This requirement does not apply to Music + Videos Hub applications that are described in Section 6.4
The Setup
You have a MediaElement
which only used to play back one file, so you set the Source
in your XAML.
The Sting
The user starts playing some music in Zune, then launches your XAP. As soon as your XAML loads and the MediaElement
's Source
is set, the background music stops playing, even if the MediaElement
is not playing. That's right, even if you set AutoPlay = "False"
, the background music will still be stopped.
Since you must ask the user for consent, you will have failed certification.
The Solution
- Never set a
MediaElement
's Source in XAML, unless that XAML is on a page that you navigate to after asking the user for consent. - Check to see if background music is playing and then set the source (in code).
Note: If you set the source and then immediately callPlay()
, thePlay()
will have no affect since theMediaElement
will still be in the"Opening"
state, instead set"AutoPlay = true"
(works from code)
Comments
- Anonymous
December 15, 2010
Thanks for this!