Playing A Sound, Simplified

Windows Phone Tutorial

In a previous posting I discussed how to play a sound using a background process.  That is great when you need the sound to continue playing even if you leave your application. But much of the time you need something far simpler: just the ability to play a sound and be done with it.

For that, all you need is to add a MediaElement to your Xaml.  In the following sample we place two buttons on the MainPage; one to start playing the sound and one to stop it.

The trick is also to add an invisible MediaElement to the Xaml, which will be the control on which you’ll call such methods as Play() and Stop().

Here’s the content panel from the Xaml:

      Source="/dtmf.mp3" />
         Click="PlayButton_Click" />
         Click="StopButton_Click" />



Note that the file I’m using for sound is one I created in Audacity:  dtmf.mp3; but you can use any handy .wav, .wma, .mp3 or .aac media file.

In the codebehind we simply reference the Media Element calling its Start() and Stop() buttons respectively. 

public MainPage()

private void PlayButton_Click( object sender, RoutedEventArgs e )

private void StopButton_Click( object sender, RoutedEventArgs e )


That’s all there is to it.  If you want to play a different sound than the one you hard coded in the Xaml, you can programmatically change it using the SoundPlayer’s SetSource method.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials, Mango, Mini-Tutorial, WindowsPhone and tagged . Bookmark the permalink.

6 Responses to Playing A Sound, Simplified

  1. Pingback:

Comments are closed.