In my last post I had explained you how to play a media file in Windows phone app using Media element control.
But when you want to play a continuous audio in the background you may face a problem as you navigate from one page to another as music will stop when you leave the page where the mediaelement control is defined. To overcome this problem one way is to define the Mediaelement globally. So in this post I shall be explaining you about how to define a global media element in Windows phone application.
1. First create a new blank project GlobalMediaelement.
2. Then add a new page to the application having the name Page1.xaml.
3. Now we need to add a Gloabal Media Element to our Application. So Open the page App.xaml and add the following code given below.
4. Now open the page App.xaml.cs and add the following code given below globally in the page.
This code is used to define the Mediaeneded event handler of the Mediaelement which will restart the song as it ends. You can manipulate it according to your needs.
5. Now add three buttons on the MainPage. The first button is used to play the audio, second one is used to stop the audio and third one is to navigate to Page1.xaml.The code for click event handlers of the buttons are given below.
6. Now run the application on emulator. And Click on the play button. You will hear a background audio running in your application.
Now as you navigate on to Page1.xaml you will see that Background music will not stop and will be played continuously.
I hope this post will be helpful to you. You can download the full project source file from the link given below.
Download full project source file GlobalMediaElement.zip