Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    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.