Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Lag noticed when playing audio

Discussion in 'Audio & Video' started by Maguelonne19, May 1, 2015.

  1. Maguelonne19

    Maguelonne19

    Joined:
    Jan 29, 2015
    Posts:
    8
    Hello,

    First time using audio in unity, the sound is playing constantly, i want the frequency to change when i hit the button "change frequency". This works fine but there is a 0.4seconds lag. Any idea why ?

    I use this function audio.create (doc here http://docs.unity3d.com/ScriptReference/AudioClip.Create.html)
    and pcmreadercallback :

    here is the code :

    Code (CSharp):
    1.  
    2.  
    3. void Start()
    4. {
    5.       audio = GetComponent<AudioSource>();
    6.       audio.loop = true;
    7.       audio.clip = AudioClip.Create("Stream", 120, 1, audioSamplingFreq, true, onReaderCallback);
    8.       audio.Play();
    9. }
    10.  
    11. private bool  low_f=false;
    12.  
    13. void onReaderCallback(float[] data)
    14.    {
    15.        for (var i = 0; i < data.Length; i++, t++)
    16.        {
    17.            float f;
    18.  
    19.            if (low_f)
    20.                f = 600;
    21.            else
    22.                f = 800;
    23.  
    24.            data[i] = 0.2f * (float)Math.Sin(2.0f * (float)Math.PI * f * (float)t / audioSamplingFreq);
    25.        }
    26.      
    27.    }
    28.    
    29.     void OnGUI()
    30.     {
    31.         if (GUI.Button(new Rect(Screen.width - 135, 40, 100, 25), "change frequency"))
    32.         {
    33.             low_f = !low_f;
    34.         }
    35.     }
     
  2. ttww

    ttww

    Joined:
    Nov 9, 2013
    Posts:
    5
    Looks like a natural consequence of the fact that the reader reads the data in chunks. onReaderCallback is called every time a new block of data is needed so your frequency is not changed until the next block read. The bigger the size of the block, the longer it is, therefore the bigger the latency.