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.
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?
does this work on the wp7 emulator?
Exactly what I was looking for! thanks!
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.
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.