Sound on keypress, not working

No Javascript experience here so bare with me. I have a spacecraft, and need it to make an acceleration sound everytime it accelerates. The accelerate key is “z”, but I want the sound to stop when you let go of the “z” key.

So here’s the code I have but it’s not working, there is no sound whatsoever:

    var sound : AudioClip;
     
    function Update()
    {
     
    if (Input.GetKeyDown ("z"))
    {
    audio.PlayOneShot(sound);
    }
     
    else
    {
    audio.PlayOneShot(sound);
    audio.Pause();
    }
     
    }

I attached an Audio Source to a empty game object, then applied the script to the empty game object with the correct sound specified.
One other issue is the spacecraft can also be controlled by a joystick. The acceleration key is “joystick button 1”, how can I trigger that sound by both the keypress AND joystick button?
Any help would be very much appreciated.

The function GetKeyDown() works only once after button is pessing. Besides in your condition you always stop audio playback by the function Pause(). I will write a small script:

 var sound : AudioClip;
 private var myAP: boolean;

 function Start() {
  myAP = false;
 }

 function Update() {
  //Change function GetKeyDown() on GetKey()
  if (Input.GetKey (KeyCode.Z) || Input.GetKey(KeyCode.JoystickButton1)) {
   if(!myAP) {
    myAP = true;
    audio.PlayOneShot(sound, 1.0);
   }
  } else {
   myAP = false;
   audio.Pause();
  }
 }

I hope that it will help you.

Update() executes every frame so your sound plays but on the next frame
it will pause because you just set it like that audio.Pause(); so that’s how
you never here anything