Blograby

Sound Playback

As an alternative to playing sounds using the media controls described in the section “Media” earlier in this chapter, you can use the XNA interop feature to initiate sound playback. This uses two of the XNA framework classes: SoundEffect and SoundEffectInstance.

To play sounds using the XNA framework classes, you must do the following:

The simplest approach is to create a SoundEffect instance and load it with a stream that points to a valid .wav file, then call the Play method of the SoundEffectInstance returned from the Create Instance method. The following code example loads a .wav file from isolated storage on the device and plays it once. To use this code, you must reference the namespaces System.IO and System.IO. IsolatedStorage.

C#
IsolatedStorageFile myStore =
IsolatedStorageFile.GetUserStoreForApplication();
Stream dat = myStore.OpenFile(“MyWavFile.wav”, FileMode.Open,
FileAccess.ReadWrite);
SoundEffect effect = SoundEffect.FromStream(dat);
effect.CreateInstance().Play();

If you want to repeat the sound, apply transformations, or specify the volume setting, you can create a SoundEffectInstance and set its properties before calling the Play method.

C#
SoundEffect effect = SoundEffect.FromStream(dat);
SoundEffectInstance sei = effect.CreateInstance();
sei.IsLooped = true;
sei.Pan = (float)0.5;
sei.Pitch = (float)-0.3;
sei.Volume = (float)0.6;
sei.Play();

 

Exit mobile version