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. Param says:

    When I try to run the same by setting the source of mediaelement in c# rather than xaml, it doesn’t play the sound if autoplay is set to false.. Any idea how it can be fixed?

  2. Anonymous says:

    does this work on the wp7 emulator?

  3. Luke Dickinson says:

    Exactly what I was looking for! thanks!

  4. Ken Roberts says:

    I all ready learnt what your teaching me.
    What I need to learn is How to get the one button to do two compleaty different jobs at the same time with the one button click.

  5. Pingback:

  6. FreakBlogger says:

    i must say that i like the way you write your tutorial articles.As wp7 is an emerging trend i found your blog contributes much to the tech community. I also run Mobile App Marketing blog intented to provide tips and news on mobile app promotions.

Comments are closed.