Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Wrong number of channels in OnAudioFilterRead

Discussion in 'Audio & Video' started by pelaezjorge, Nov 25, 2020.

  1. pelaezjorge

    pelaezjorge

    Joined:
    Aug 3, 2020
    Posts:
    8
    Good morning!
    I'm sorry if this has been asked before.

    The thing is that I'm using OnAudioFilterRead function to generate a stream of audio. So, despite of be using Speaker Mode = Stereo, the number of channels in OnAudioFilterRead is 1. As I understand, the number of channels should match the mode (2 in this case).

    The weird part is that this problem does not appear always. Usually the number of channels is 2. Sometimes I can fix it changing Speaker Mode to Mono and then back to Stereo, but other times I can't.

    I tested in Unity 2019.4.10f1 and 2019.4.15f1 with same result.

    Am I missing some configuration somewhere?

    Thank you!
     
  2. pelaezjorge

    pelaezjorge

    Joined:
    Aug 3, 2020
    Posts:
    8
    Okay, I got how to reproduce the situation.

    OK - Initially, a 2-channel device is used. OnAudioFilterRead uses 2 channels.
    OK - Hardware is changed to a 1-channel device. OnAudioFilterRead uses 1 channel.
    NOT OK - Hardware is changed back to a 2-channel device. OnAudioFilterRead uses 1 channel.

    Changing Speaker Mode to Mono and then back to Stereo seems to solve the problem.

    This is not during playmode. Changing the devices with the open editor will keep the config in different runs.

    EDIT: Seems that it can be solved during runtime checking if channel number is correct. If its not correct, just execute something like this (in the main thread, not audio thread).

    Code (CSharp):
    1.         AudioConfiguration audioConf = AudioSettings.GetConfiguration();
    2.         audioConf.speakerMode = AudioSpeakerMode.Mono;
    3.         AudioSettings.Reset(audioConf);
    4.  
    5.         yield return null;
    6.  
    7.         audioConf.speakerMode = audioSpeakerMode;
    8.         AudioSettings.Reset(audioConf);
    9.        
    10.         AudioSource s = GetComponent<AudioSource>();
    11.         s.Stop();
    12.         s.Play();