- Home /
Fade audio in and out for Jet Engine
Hi,
I would an audio clip to quicly fade-in and then play (continous sound) when a certain key is pressed, and then for the sound to quickly fade-out and pause when the key is released. I have attempted to get this to work with animation, but the fade-out part doesn't work.
Any ideas?
I created two animations, one which faded the volume in, and the other faded it out. I tried to call these at the relevant times in my code. The audio clip is assigned to the audio source in the inspector.
My attempt at code:
if (Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ) ){
animation.Play("animationJetOn");
if(jetAudio){
audio.Play();
}
}else if ( !Input.GetButton( "Horizontal" ) && !Input.GetButton( "Vertical" ) && audio.isPlaying){
animation.Play("animationJetOff");
WaitForSeconds(0.25);
if(jetAudio){
audio.Pause();
}
}
Answer by aldonaletto · Sep 08, 2012 at 05:21 AM
I would do the following: set the fields Play On Awake and Loop in the AudioSource, so that the jet sound would be playing continuously, and control only its volume (the sound should be loopable, of course). I would also change a little the logic to ease detecting when the jet is turning on and off, like this:
var fadeInTime: float = 0.25; var fadeOutTime: float = 2.5;
private var jetOn = false; private var vol: float = 0;
function Update(){ var oldJet = jetOn; // save last jetOn state to detect changes jetOn = Input.GetButtonDown("Horizontal") || Input.GetButtonDown("Vertical"); if (jetOn != oldJet){ // if jetOn changed... if (jetOn){ // start the suitable animation animation.Play("animationJetOn"); } else { animation.Play("animationJetOff"); } } if (jetAudio){ if (jetOn){ // fade in/out the sound according to jetOn: vol += Time.deltaTime / fadeInTime; } else { vol -= Time.deltaTime / fadeOutTime; } vol = Mathf.Clamp(vol, 0, 1); // keep it in the 0..1 range audio.volume = vol; // update the actual audio volume } }