Playing a sound effect

Applies to Windows and Windows Phone

Here are code samples for playing an audio file, such as a sound effect.

Sound effects can add useful feedback to an app, or add to the atmosphere in a game. In iOS, you may have used AudioServicesCreateSystemSoundID to trigger short sound samples. To play audio files under Windows 8 using C#, use the following XAML to create a MediaElement object:


 <MediaElement x:Name="bleep" AudioCategory="GameEffects" Source="Assets/bleep.wav" AutoPlay="False" Visibility="Collapsed"/>

Then trigger the sound (perhaps when the user taps a button), with a method in the code behind file, like this:


 private void Button_Click(object sender, RoutedEventArgs e)
        {
            bleep.Play();
        }

MediaElement can do a lot more than simply play back audio files – you can use it to embed video in your app, and even stream it to other devices on your network. For info, see Quickstart: video and audio (Windows Store apps using C#/VB/C++ and XAML).

Note  To play sound in the background, for example, streaming music, see How to play audio in the background.

To trigger the playback a sound file from within your JavaScript app, use code like this:


	var sound = document.createElement("audio");
        sound.src = "/sounds/bleep.wav";
        sound.autoplay = true;


Related topics

Topics for iOS devs
Resources for iOS devs
Windows 8 controls for iOS devs
Windows 8 cookbook for iOS devs
Audio topics
AudioCategory enumeration
Quickstart: adding audio to an app (Windows Store apps using JavaScript and HTML)

 

 

Show:
© 2015 Microsoft