This project is read-only.

Playing sound

Oct 26, 2009 at 7:15 AM
Edited Oct 26, 2009 at 7:18 AM

Hi Ohan,

I'm having some problems with sound playing. I'm triyng to play an engine sound for a car which do as follow:

If I press up arrow or down arrow from the keyboard, it should play the engine sound in looping. If I release them it should pause playing. However, if I keep pressing the button, it loads the engine sound several times overloading the system until it freezes. This is what I've made:

 

if (keyboard.IsKeyDown(Keys.Up) || keyboard.IsKeyDown(Keys.Down))
{   
   if (Sound.Play("motor2") == null)
   {
      Sound.Play("motor2");                        
   }
   else if (Sound.Play("motor2").IsPaused)
   {
      Sound.Play("motor2").Resume();
   }
   else if (Sound.Play("motor2") != null && Sound.Play("motor2").IsPlaying)
   {
      Sound.Play("motor2").Pause();
   }
}

What Am I doing wrong? I'm using XACT 2.0 and Goblin XNA v3.2.

 

Thanks,

 

Emerson

Coordinator
Oct 27, 2009 at 11:01 PM

Every time you call Sound.Play(..), it will play the sound no matter whether it's already playing or not, because it is designed to be able to play the same sound multiple times with overlap. What you should do is to get the Cue returned by Sound.Play(...) and check the status using the returned cue instance. 

What you want to do is probably the following:

Cue cue; // initialize this somewhere in your class

then, in your Update section:

KeyboardState state = Keyboard.GetState();
if(state.IsKeyDown(Keys.Up) || state.IsKeyDown(Keys.Down))
{
    if (cue == null || cue.IsDisposed)
         cue = Sound.Play("motor2");
    else if (cue.IsPaused)
         cue.Resume();
}
else if (state.IsKeyUp(Keys.Up) || state.IsKeyUp(Keys.Down))
{
    if (cue != null && cue.IsPlaying)
         cue.Pause();
}

 

Ohan

KeyboardState state = Keyboard.GetState();
            if(state.IsKeyDown(Keys.Up))
            {
                if (cue == null || cue.IsDisposed)
                {
                    cue = Sound.Play("rubber_ball_01");
                }
                else if (cue.IsPaused)
                    cue.Resume();
            }
            else if (state.IsKeyUp(Keys.Up))
            {
                if (cue != null && cue.IsPlaying)
                    cue.Pause();
            

 

 

Oct 28, 2009 at 2:56 PM

Hi Ohan,

Thanks for your help, it solved my problem!

 

Emerson