Play Background music in Windows Phone app C# code

We want to play background sound in our Windows Phone app, we can play using this below objects.

1) MediaElement — need to include phone.controls dll

2) SoundEffect  – need to include XNA framework dlls

Play Sound In Windows Phone App
Play Sound In Windows Phone App

To Play Sound in background first we have to please audio file in our project. in my case I placed those audio file in Sounds folder. Then in Solution Explore right click on add audio file and go to Properties . In Build Action, set value to Content. Copy to Output Direct value to Copy if newer.

FrameworkDispatcher.Update();  //We have Update FrameworkDispatcher to play sound using SoundEffect

To Load Audio file:-

private SoundEffect soundeffObj;
LoadSoundFile("sounds/filename.wav", out soundeffObj);
private void LoadSoundFile(String FilePath, out SoundEffect Sound)
{
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(FilePath, UriKind.Relative));
// Create the SoundEffect from the Stream
Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
}
catch (NullReferenceException)
{
// Display an error message
MessageBox.Show("unable to load sound file from this path :" + FilePath);
}
}

Now soundeffObj object hold the Audio file, to play this audio file we can use .Play() method. Like this

soundeffObj.Play()

We can also play using MediaElement, check this code
I added Media Element in XAML code itself in my demo app. We can also add in runtime. Here is my XMAL code

mediaEle.Source = new Uri("sounds/Sleep Away.mp3", UriKind.Relative);
mediaEle.Volume = 1f;
mediaEle.MediaEnded += new RoutedEventHandler(mediaEle_MediaEnded); // To handle finish event
mediaEle.Visibility = Visibility.Collapsed;

Media Element Media Ended event:
private void mediaEle_MediaEnded(object sender, RoutedEventArgs e)
{
//Do something here
}

I upload my code to Github https://github.com/rish7/WindowsPhonePlaySound/
We can also Zune pause and resume, using our code lines. This code also presented in it.

Enjoy while coding..!

Leave a Reply