Windows Phone 8: MediaElement fails to play under Lock Screen – Workaround

Disclaimer!:  I am not a Window Phone Expert though dabble occasionally…

Summary

The Media Element on Windows Phone 8 sometimes/often fails to play media under the lock screen.  Forcing a layout update works around the problem.

Scenario

My app features several pages that load automatically in a sequence to play various pieces of audio.  (These same pages do other things too when the phone is unlocked, but when locked everything else is disabled except the playing of the audio).

Each page plays a piece of audio using the Media Player.  On some pages the audio was playing happily under the lock screen.  On other pages the audio refused to play (no error, the call to the media player was seemingly ignored).

Investigation

After several hours of comparing the pages I tracked down the single line of code that was making the difference.  On pages where the audio was playing, the following line was present and this single line made the all important difference:

myPivotControl.Items.Remove(myPivotItemTobeRemoved);

Guessing that this might be triggering a layout update, I swapped this line for the following:

ContentPanel.UpdateLayout();

Same effect.  When this line was executed before the call to the MediaPlayer element, the audio played.  If I skipped calling this line, the audio didn’t play.

Download

The simple project I used to explore this issue can be downloaded here.  Leaving the “Force Layout Updates” box unticked demonstrates the problem.  Ticking the box runs the extra line of code and the audio plays fine.

Note

I haven’t tested this on the latest version of the WP8 Emulators.  I have however tested it on my Lumia 920 which is running the latest updates and the behaviour is the same.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s