XNA Creators Club Online
Page 1 of 1 (1 items)
Sort Posts: Previous Next

Why does my sound cut out before it is finished

Last post 07-10-2007 12:18 PM by The ZMan. 0 replies.
  • 07-10-2007 12:18 PM

    Why does my sound cut out before it is finished

    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:

    1. 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
    2. If you don't actually need an instance of the cue for other reasons then use the soundbank.PlayCue() method.
    3. 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();
    }
    }

    The ZBuffer News and information for XNA
    Please read the forum FAQs - Bug reporting
Page 1 of 1 (1 items) Previous Next