Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Audio High-Frequency Audio-Visual Synchronization

Discussion in 'Audio & Video' started by maxronc, Apr 8, 2024.

  1. maxronc

    maxronc

    Joined:
    Apr 10, 2021
    Posts:
    2
    Greetings everyone,

    I'm encountering a technical challenge with a rather unique project, and after numerous experiments, I'm seeking the advice of those more experienced than myself to explore potential solutions I may not have yet considered.

    I have a scene with a quad that alternates between black and white with each frame. My objective is to have a pure tone play every time the quad is displayed in white. The desired outcome is to achieve synchronous blinking between the image and the sound.

    To accomplish this, I've attempted to generate a sound using AudioClip.Create, which continuously plays the tone, and I've implemented a command in the Update function to manage the quad's color switch. I've also added audioSource.volume = isWhite ? 1.0f : 0.0f;.

    However, the current result is far from satisfactory as the sound does not synchronize with the image, and it feels like there is something too heavy to be managed in real-time.

    I really want the sound to depend on the frame, and I'm looking for the most low-level method to achieve optimal results. Do you have any other avenues to consider?
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    454
    Have you tried looking at OnAudioFilterRead? Within Unity regular features, I think it's the simplest way to make reactive audio.
     
  3. maxronc

    maxronc

    Joined:
    Apr 10, 2021
    Posts:
    2
    Thank you SeventhString for the response.

    I tried implementing that method. I can generate my pure tone, but it seems I still have a delay that I need to compensate for to ensure the sound plays when the frame is blank. I'm trying to add a delay in the buffer to play the sound with a one-frame delay but at an accurately calibrated position. Do you think this is possible? Currently, my code doesn't seem to work because no matter what I put in for audioDelayInSeconds, the delay seems to always be the same.

    This plot shows the reading of a light sensor placed on the screen and the audio signal from the jack cable:


    Here is my code:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SimpleColorBlinkAndContinuousToneWithDelay : MonoBehaviour
    4. {
    5.     private Material objectMaterial;
    6.     private bool isWhite = false;
    7.     public int framesBetweenSwitch = 1;
    8.     private int frameCounter = 0;
    9.     private int sampleRate;
    10.     public float toneFrequency = 440f;
    11.  
    12.     private float[] delayBuffer;
    13.     private int writeIndex = 0;
    14.     private int readIndex = 0;
    15.     public float audioDelayInSeconds = 0.1f;
    16.  
    17.     public float activeTime = 5f;
    18.     public float pauseTime = 5f;
    19.     private float activeTimer;
    20.     private float pauseTimer;
    21.     private bool isActive = true;
    22.  
    23.     void Start()
    24.     {
    25.         objectMaterial = GetComponent<Renderer>().material;
    26.         sampleRate = AudioSettings.outputSampleRate;
    27.         int delaySamples = (int)(audioDelayInSeconds * sampleRate);
    28.         delayBuffer = new float[delaySamples];
    29.         writeIndex = 0;
    30.         readIndex = (writeIndex - delaySamples + delayBuffer.Length) % delayBuffer.Length;
    31.     }
    32.  
    33.     void Update()
    34.     {
    35.         if (isActive)
    36.         {
    37.             activeTimer -= Time.deltaTime;
    38.             if (activeTimer <= 0)
    39.             {
    40.                 isActive = false;
    41.                 pauseTimer = pauseTime;
    42.             }
    43.         }
    44.         else
    45.         {
    46.             pauseTimer -= Time.deltaTime;
    47.             if (pauseTimer <= 0)
    48.             {
    49.                 isActive = true;
    50.                 activeTimer = activeTime;
    51.             }
    52.         }
    53.  
    54.         if (isActive)
    55.         {
    56.             frameCounter++;
    57.             if (frameCounter >= framesBetweenSwitch)
    58.             {
    59.                 frameCounter = 0;
    60.                 isWhite = !isWhite;
    61.                 objectMaterial.color = isWhite ? Color.white : Color.black;
    62.             }
    63.         }
    64.         else
    65.         {
    66.             objectMaterial.color = Color.black;
    67.         }
    68.     }
    69.  
    70.     void OnAudioFilterRead(float[] data, int channels)
    71.     {
    72.         for (int i = 0; i < data.Length; i += channels)
    73.         {
    74.             float sampleValue = Mathf.Sin(2 * Mathf.PI * toneFrequency * i / sampleRate) * (isActive && isWhite ? 1.0f : 0.0f);
    75.             delayBuffer[writeIndex] = sampleValue;
    76.  
    77.             for (int channel = 0; channel < channels; channel++)
    78.             {
    79.                 if (i + channel < data.Length)
    80.                     data[i + channel] = delayBuffer[readIndex];
    81.             }
    82.  
    83.             writeIndex = (writeIndex + 1) % delayBuffer.Length;
    84.             readIndex = (readIndex + 1) % delayBuffer.Length;
    85.         }
    86.     }
    87. }
    88.  
    Thanks
     
    Last edited: Apr 16, 2024
  4. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    454
    I'm not really sure why it wouldn't work right there....
    A thing we need to keep in mind is that Start and Update are not running on the same thread than OnAudioFilterRead. This latter one is called back from the audio thread so the values of your write/read indices might suffer from that.
    I think you should keep readIndex to 0 in the start and wait for the audio buffer to fill at least that much data in your delay buffer before starting to write data to the callback output. Although that's just a hunch....
     
  5. dynamicbutter

    dynamicbutter

    Joined:
    Jun 11, 2021
    Posts:
    81
    Hello @maxronc, I think you can keep your OnAudioFilterRead the same (almost) and sync your flash off of the audio thread.

    One way to do that would be to push alternating white/black messages to a queue from the audio thread and have the main thread Update function poll the queue for color changes.

    Something like this...

    Code (CSharp):
    1. using System.Collections.Concurrent;
    2.  
    3. public class SimpleColorBlinkAndContinuousToneWithDelay : MonoBehaviour
    4. {
    5.     const float SECONDS_BETWEEN_TOGGLE = .5f;
    6.     int BuffersBetweenToggle;
    7.     int bufferCount;
    8.     enum ColorMessage
    9.     {
    10.         White,
    11.         Black,
    12.     }
    13.     ConcurrentQueue<ColorMessage> colorQueue = new ConcurrentQueue<ColorMessage>();
    14.     bool Ready;
    15.     ...
    16.  
    17.     void Start()
    18.     {
    19.         ...
    20.         BuffersBetweenToggle = SECONDS_BETWEEN_TOGGLE *
    21.             AudioSettings.outputSampleRate /
    22.             AudioSettings.dspBufferSize;
    23.         Ready = true;
    24.     }
    25.  
    26.     void Update()
    27.     {
    28.         while (colorQueue.TryDequeue(out transitionColor))
    29.         {
    30.             if (colorQueue.Count > 0)
    31.             {
    32.                 // Should only have 1 message unless something got paused,
    33.                 // to be safe, don't let q messages build up
    34.                 continue;
    35.             }
    36.             if (transitionColor == ColorMessage.White)
    37.             {
    38.                 objectMaterial.color = Color.white;
    39.             }
    40.             else
    41.             {
    42.                 objectMaterial.color = Color.black;
    43.             }
    44.         }
    45.     }
    46.  
    47.     void OnAudioFilterRead(float[] data, int channels)
    48.     {
    49.         if (Ready) {
    50.             bufferCount++;
    51.             ...
    52.             if (bufferCount % BuffersBetweenToggle == 0)
    53.             {
    54.                 colorQueue.Enqueue(isActive ? ColorMessage.White : ColorMessage.Black);
    55.                 isActive = !isActive;
    56.             }
    57.         }
    58.     }
    59. }
    You can control the flash rate by changing the value of SECONDS_BETWEEN_TOGGLE (which I have arbitrarily set to 0.5). I have not tested this code so there are certainly bugs ;)
     
    Last edited: May 1, 2024
    SeventhString likes this.