The most common reason for sounds cutting out is using a local variable to store the cue for your sound. Local variables go out of scope at the end of a function and are become candidates for collection by the garbage collector. At some non determinate point in the future when the GC runs it will collect the cue and the sound will cut out.
In addition you may see sound glitches if you do not call the Update method on AudioEngine
(See also Shawns blog on the subject)
There are 3 solutions:
- Use a variable which will not go out of scope for the duration you need the sound to be played - make it class level or even static
- If you don't actually need an instance of the cue for other reasons then use the soundbank.PlayCue() method.
- Ensure you call AudioEngine.Update inside your render loop somewhere
e.g. (thanks to Harald Maassen for the 1st version of the code)
class SomeClass
{
SoundBank soundBank;
Cue soundEffect;
static Cue soundEffect2;
public void PlayMusic()
{
//This is fairly safe - it can't be collected until the instance
//of the class goes out of scope
soundEffect = soundBank.GetCue("boom");
soundEffect.Play();
//This is very safe - static variables are not collected until
//the application closes
soundEffect2 = soundBank.GetCue("boom");
soundEffect2.Play();
//This is very safe - no collection issues but you don't have an
//instance of the cue to stop and start
soundBank.PlayCue("boom");
//This is not very safe - it can be collected as soon as this
//method ends
Cue soundEffect3;
soundEffect3 = soundBank.GetCue("boom");
soundEffect3.Play();
}
}
Play Kissy Poo - a game for 4 year olds on Xbox and windows
The ZBuffer News and information for XNA
Follow
The Zman on twitter,
Email me Please read
the forum FAQs -
Bug/Feature reporting Don't forget to mark good answers and good playtest feedback when you see it!!!