The original article has been posted here.
Introduction/Catalog
If you want to create a game for Windows Phone, then XNA is a choice. Now, I will explore and learn XNA for Windows Phone with you.
In XNA, SoundEffect
and SoundEffectInstance
are available to play the sound, such as: WAV files. But it is important to note both the SoundEffect
or SoundEffectInstance
cannot play MP3 files, you need to use the class Song
to play the MP3 files.
Shared Resources
You can load a sound file to the SoundEffect
class, you can also create a new SoundEffectInstance
object from the SoundEffect
. And these new SoundEffectInstance
objects will share the sound resource contained in the SoundEffect
.
The SoundEffect
object will keep the resource in the life cycle. Once the SoundEffect
is destroyed, the SoundEffectInstance
objects which it created will fail, when you call the method Play
.
private ContentManager contentManager;
private SoundEffect mySound;
private SoundEffectInstance mySound1;
private SoundEffectInstance mySound2;
protected override void LoadContent ( )
{
spriteBatch = new SpriteBatch ( GraphicsDevice );
if ( null == this.contentManager )
this.contentManager = new ContentManager ( Services, "Content" );
this.mySound = this.contentManager.Load<SoundEffect> ( @"mysound" );
this.mySound1 = this.mySound.CreateInstance ( );
this.mySound2 = this.mySound.CreateInstance ( );
}
protected override void UnloadContent ( )
{
this.mySound1.Dispose ( );
this.mySound2.Dispose ( );
this.mySound.Dispose ( );
this.contentManager.Unload ( );
}
If we release the mySound
object in the Update
method, there will be an error when you call the Play method of the mySound1
or mySound2
.
protected override void Update ( GameTime gameTime )
{
this.mySound.Dispose ( );
this.mySound1.Play ( );
}
Repeat
Either the SoundEffect
or SoundEffectInstance
, the sound can't play again before finished. If you call the Play
method in the Update
method, the sound will only play again until it is finished playing.
protected override void Update ( GameTime gameTime )
{
this.mySound.Play ( );
}
If you want to play the sound again when it's playing, you can define multiple SoundEffectInstance
objects.
Total Number of Sounds
On Windows Phone, XNA can play a total of 16 sounds at one time.
Stop Playing
Since the SoundEffect
only plays smaller sound file, under normal circumstances, it is not going to stop playing the sound. But sometimes if you're in the loop, may have to use the Stop
method. To stop the sound, you need through the SoundEffectInstance
class.
protected override void Update ( GameTime gameTime )
{
int seconds = ( int ) gameTime.TotalGameTime.TotalSeconds;
if ( seconds > 5 )
{
if ( this.mySound1.State != SoundState.Stopped )
this.mySound1.Stop ( );
}
else
if ( this.mySound1.State == SoundState.Stopped )
{
this.mySound1.IsLooped = true;
this.mySound1.Play ( );
}
}