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. Dismiss Notice

OnAudioFilterRead and sample rates

Discussion in 'Audio & Video' started by Luke_161, Sep 20, 2016.

  1. Luke_161

    Luke_161

    Joined:
    Mar 3, 2015
    Posts:
    19
    Hello all,

    I've been using OnAudioFilterRead to create a rewind/fast-forward effect on procedurally generated audio, the script moves a playhead (sample position) based on user interaction (forward/back) and reads from a float[] buffer.

    It works nicely, but I'm having issues with the sample rate on different platforms. From what I can tell OnAudioFilterRead runs at the same sample rate as AudioSettings.outputSampleRate, which varies from platform to platform (48000 on desktop, 24000 on iOS for example).

    The procedural audio is generated from existing AudioClips that have a sample rate of 48000, but on platforms where the sample rate is different the audio is falling out of sync.

    I've fixed this by forcing the sample rate to 48000 on all platforms, but I'm wondering if there's anyway in Unity to change a clips sample rate at runtime? Or a way to change the rate OnAudioFilterRead samples at to match my clip?

    Just to add, I tried building the effect with AudioClip.PCMReaderCallback, but the buffering produced to much latency.

    Thanks!
     
  2. 00christian00

    00christian00

    Joined:
    Jul 22, 2012
    Posts:
    1,033
    If I remember correctly, you need to create an Audioclip with the sample rate you want and start playing it. This way you can use onAudioFilterRead at the sample rate you want.
    Careful that there is a bug that allocate temp buffer continuously when using onAudioFilterRead, causing the GC to fire practically every second and the devs says it won't be fixed soon.
     
  3. Zicandar

    Zicandar

    Joined:
    Feb 10, 2014
    Posts:
    388
    @00christian00 I'm trying to do that trick with having a AudioClip with the sample rate I want, however it still seems to be running the OnAudioFilterRead as the sample rate that is set in the AudioSettings. Also thank you for pointing out the garbage collection bug, I was not aware of it.
    @Luke_161 The bug with the massive buffer is in part due to FMOD, as they by default allocate 400ms worth of buffering to procedural sounds. (And ask for samples that often). Resulting in a very high latency as you have noticed. If you find a working solution on Unity 5.3.4 please post so here!