Audio issues when playing different looping audio.

Hi guys, I’ve got a basic character that I want to have play a sound when moving & one when not, I’ve got the code to make the sounds play separately, using AudioSource, they are separate AudioSources, yet when running they play, but with what can only be thought of as it trying to play the clip each frame. How do I play one looped audio when something == true? and play something else when not? this is extremely simple I’m assuming but cannot for the life of me figure it out!

I’m using

var coasting : AudioSource;
var pedallingAudio : AudioSource;


if(pedalling == true){
coasting.Play();
}else{
pedallingAudio.Play();
}

it sounds as if it is the second sound trying to play every frame. Many thanks in advance!

Dan

You should not call Play every Update: this restarts the sound instead of loop it, what produces an awful sound. You should instead check Play On Awake and Loop in the Inspector in both sounds to make both run continuously, and set mute=false to control which one will sound:

  if (pedalling){ 
    coasting.mute = false;
    pedallingAudio.mute = true; 
  } else {  
    coasting.mute = true;
    pedallingAudio.mute = false;
  }

This works fine for continuous sounds like wind, water, motor etc. If you need to start the sound each time it’s selected, things are more complex: you must detect when pedalling changes state, and Play one and Stop the other:

private var oldState = false;
...
  if (pedalling != oldState){ // if changed state...
    oldState = pedalling; // update oldState...
    if (pedalling){  // and play/stop the correct sounds
      coasting.Play();
      pedallingAudio.Stop();
    } else {  
      coasting.Stop();
      pedallingAudio.Play();
    }
  }
  ...