Search code examples
windows-phone-8

Playing Soundbite in WP8 App


I'm trying to write a WP8 app that plays a short sound when a button is pressed, but I cannot seem to figure out how to play the sound. Here's a quick example of my code:

XAML

<Rectangle x:Name="Rect1" Grid.Row="0" Grid.Column="0" Tap="RectTapped" Fill="White" />

App.cs

private void RectTapped(object sender, System.Windows.Input.GestureEventArgs e)
{
    MediaElement sound = new MediaElement();
    sound.AutoPlay = false;
    sound.Source = new Uri("Assets\\Sounds\\bark-1.wav", UriKind.Relative);
    sound.Play();
}

When testing on my Nokie 820 device no sound plays. I can't understand why.

Is there something I'm doing wrong? The .wav is in my resources.

I've read that MediaElement shouldn't be used for this task. I've tried using the SoundEffect class in Xna.Framework.Audio; following the example from MSDN but that also fails because I couldn't use Content.Load as Load was not an available method of the Content class.

I've also looked at XAudio2, but as I do not know C++ I can't get my head around the examples.


Solution

  • Instead of a Rectangle, use a Button. Also, MediaElement is good for playing short sounds in Silverlight applications. Make sure that the control is a part of your visual tree (add it in XAML). Then bind to the button Click event handler:

    private void YourClickHandler(object sender, RoutedEventArgs e)
    {
       myMediaElement.Source = new Uri("/Assets/Sounds/bark-1.wav", UriKind.Relative);
       myMediaElement.Play();
    }