We have introduced SoundEffect for playing audio on Windows Phone. However, this method can only play audio in WAV format. The following describes a lightweight, easy-to-use method that supports multiple formats and can be loaded directly from the Uri. You can use MediaPlayer and Song to play audio. These two classes also belong to the XNA Framework, so you need to add references to Microsoft. Xna. Framework.
1. Because every 33fp in XNA will Update the screen once, you need to specify a scheduled FrameworkDispatcher. Update () event in Silverlight Application.
// Set the timer
DispatcherTimer timer = new DispatcherTimer ();
Timer. Interval = TimeSpan. FromMilliseconds (33 );
Timer. Tick + = delegate {try {FrameworkDispatcher. Update ();} catch {}};
Timer. Start ();
2. Create an audio object through Song and play it through MediaPlayer.
Try
{
// Create an audio object
Song song = Song. FromUri ("Music", new Uri ("/Song/yuled", UriKind. Relative ));
// Set it to loop playback.
MediaPlayer. IsRepeating = true;
// Start playing
MediaPlayer. Play (song );
}
Catch (System. Exception ex)
{
// An error occurred while creating the audio object. The uri is incorrect.
}
3. Pause, reset, and stop the audio.
// Pause
MediaPlayer. Pause ();
// Reset
MediaPlayer. Resume ();
// Stop
MediaPlayer. Stop ();
4. Set the audio playback volume.
// The volume value ranges from 0 to 1. The default value is 0.85 and the value is 0.5.
MediaPlayer. Volume = 0.5F;
Song and MediaPlayer can be used to play audio in multiple formats, which is quite simple and convenient to use. However, the XNA Library also needs to be introduced, and the audio file used to create a Song object through Song. FromUri can only be a resource file, not a file in independent storage. For files in independent storage, no API for creating Song objects is found yet, and we hope to discuss it with everyone.