Search Unity

Callback for AudioClip finished

Discussion in 'Scripting' started by Gang-Fang, Jun 13, 2014.

  1. Gang-Fang

    Gang-Fang

    Joined:
    Jan 20, 2014
    Posts:
    6
    Hi here, I'm a newbie to Unity3D, currently using free version of U3D.
    And I want to do something when a specific audioclip play to the end... But I just found
    Code (CSharp):
    1.         public delegate void PCMReaderCallback(float[] data);
    2.  
    3.         public delegate void PCMSetPositionCallback(int position);
    these two delegate handlers at AudioClip defination. and no one helps..
    You guys ,anyone has the same experience at this topic? just give me some advice, thanks.

    Any suggestion is appreciated!.
     
  2. ashwinFEC

    ashwinFEC

    Joined:
    May 19, 2013
    Posts:
    48
    You could try something easier using a Coroutine. See this pseudo code:

    Code (CSharp):
    1.  
    2. AudioSource source;
    3.  
    4.     void PlayAudio(AudioClip clip)
    5.     {
    6.         float clipLength = clip.length;
    7.  
    8.         source.Play(clip);
    9.         StartCoroutine(StartMethod(clipLength));
    10.     }
    11.  
    12.     private IEnumerator StartMethod(float clipLength)
    13.     {
    14.         yield return new WaitForSeconds(clipLength);
    15.  
    16.         YourCallBackMethod();
    17.  
    18.     }
     
    SametJR, Shahdee, Shadowing and 2 others like this.
  3. Gang-Fang

    Gang-Fang

    Joined:
    Jan 20, 2014
    Posts:
    6
    Thanks!
    That's really a good idea,
    But I found if I change the speed of the animationclip runtime, coroutine also don't help``
     
  4. IsGreen

    IsGreen

    Joined:
    Jan 17, 2014
    Posts:
    206
    Simply, check AudioSource Component property AudioSource.isPlaying
     
    Gang-Fang likes this.
  5. Gang-Fang

    Gang-Fang

    Joined:
    Jan 20, 2014
    Posts:
    6
    Oh yeah, that's really a way!
     
  6. Gang-Fang

    Gang-Fang

    Joined:
    Jan 20, 2014
    Posts:
    6
    Thanks for all guys above.
    Finally I know that there isn't a 'normal' way to get a callback via API from Unity3D , so I change my plan to accomplish my destination by using mechanism animator system!
    Thread Closed!.
     
    Wilhelm_LAS likes this.