Slowly fade audio's pitch on key press?

I have a really basic script for a vehicles engine sound; when you’re idle, the vehicle will player a lower pitched sound, and when you’re moving (pressing “W”) it will play a higher pitched sound. I haven’t scripted much audio in the past, and at the moment, the change is too sudden. How can I fade the pitch from the lower to high, and vice versa?

function Update () 
{
	if(Input.GetKeyDown(KeyCode.W))
	{
		audio.pitch = 0.85;
	}
	
	if(Input.GetKeyUp(KeyCode.W))
	{
		audio.pitch = 0.7;
	}

}

Lerp the value in a coroutine.

You need to fade in and out with Time.

var onlyOnce:boolean = true;

function Update () 
{
    if(Input.GetKeyDown(KeyCode.W) && onlyOnce)
    {
       onlyOnce = false;
       FadeOut(0.85f);
    }
 
    if(Input.GetKeyUp(KeyCode.W))
    {
       onlyOnce = false;
       FadeOut(0.7f);
    }
}

function FadeOut(volume:float){
   float vol = volume;
   while(audio.volume > vol){
      audio.volume -= Time.deltaTime;
      yield;
   }
   onlyOnce = true;
}

You press the button and if you have not a coroutine already running (onlyOnce) you call the coroutine. Then it decreases the audio with deltaTime, you can add a speed in the coroutine, the first parameter is the value you want to reach.

Once the value is reaced, onlyOnce is true again, you can do new calls.

I’ve figured it out now. Not sure if it’s the most efficient way of doing things, but hey, it’s Java.

function Update () 
{
	if(Input.GetKey(KeyCode.W))
	{
		audio.pitch += 0.01;
			if(audio.pitch >= 0.85)
			{
				audio.pitch = 0.85;
			}
	}
	
	if(Input.GetKey(KeyCode.W) == false)
	{
		audio.pitch -= 0.01;
			if(audio.pitch <= 0.45)
			{
				audio.pitch = 0.45;
			}
	}

}