Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Audio repeating rapidly.

Discussion in 'Audio & Video' started by TippyRook, Dec 16, 2014.

  1. TippyRook

    TippyRook

    Joined:
    Dec 16, 2014
    Posts:
    17
    So I've been trying to add a specific audio clip to certain animations using C#. So far no luck. I have one placed in my fixedupdate so it would constantly play and another in my update void so it will only play when I hold down the space bar.

    public AudioSource au_flying;
    public AudioSource au_driving;

    void Start()
    {
    au_driving = (AudioSource)gameObject.AddComponent ("AudioSource");
    AudioClip DrivingClip;
    DrivingClip = (AudioClip)Resources.Load("SFX/driving");
    au_driving.clip = DrivingClip;

    AudioClip FlyingClip;
    FlyingClip = (AudioClip)Resources.Load("SFX/flying");
    au_flying.clip = FlyingClip;
    }

    void Update ()
    {
    if (Input.GetKey (KeyCode.Space))
    {
    au_flying.Play ();
    }
    }

    void FixedUpdate()
    {
    au_driving.Play ();
    }

    So right now my au_driving isn't playing at all and when I hold space the au_flying will repeat rapidly without finishing the audio clip until I release the spacebar. I haven't found any other solution because all tutorials I found are in JavaScript.
     
  2. MakeCodeNow

    MakeCodeNow

    Joined:
    Feb 14, 2014
    Posts:
    1,246
    Both codepaths have the same problem. Input.GetKey returns true as long as the key is down. You probably want Input.GetKeyDown, which only fires when the button is first pressed. Calling Play() inside the FixedUpdate does the same thing, restarting the sound over and over. You may not hear it because maybe the beginning of the sound is quiet, but it is playing over and over. If you want something to loop, you need to just set AudioSource.loop. to true.
     
  3. TippyRook

    TippyRook

    Joined:
    Dec 16, 2014
    Posts:
    17
    Thank you for the reply, the audio is playing all the way before playing again. However their is one more issue I found. You see my au_flying sound effect, when set to loop, will loop but once I release the space button it will continue. What my intentions are is for au_flying to play only when space is being held and au_driving is always playing except when au_flying is playing. For au_flying I tried to use an else statement to stop the clip with au_flying.Stop(). However, it prevents the clip from playing. I was told an else if statement would work but I don't know how I'd set it up because the if statement is an input.getkeydown. I'm new to unity and I need and appreciate all and any help I can get.
     
  4. MakeCodeNow

    MakeCodeNow

    Joined:
    Feb 14, 2014
    Posts:
    1,246
    Play on Input.GetKeyDown() and stop on Input.GetKeyUp().