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:

<Grid
   x:Name="ContentPanel"
   Grid.Row="1"
   Margin="12,0,12,0">
   <MediaElement
      Name="SoundPlayer"
      AutoPlay="False"
      Source="/dtmf.mp3" />
   <StackPanel>
      <Button
         Name="PlayButton"
         Content="Play"
         Width="200"
         Height="85"
         Click="PlayButton_Click" />
      <Button
         Name="StopButton"
         Content="Stop"
         Width="200"
         Height="85"
         Click="StopButton_Click" />
   </StackPanel>

</Grid>

 

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()
{
    InitializeComponent();
}

private void PlayButton_Click( object sender, RoutedEventArgs e )
{
    SoundPlayer.Play();
}

private void StopButton_Click( object sender, RoutedEventArgs e )
{
    SoundPlayer.Stop();
}

 

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 online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and 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 Microsoft MVP.
This entry was posted in Essentials, Mango, Mini-Tutorial, WindowsPhone and tagged . Bookmark the permalink.

5 Responses to Playing A Sound, Simplified

Comments are closed.