Legacy Documentation: Version 5.5
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

MonoBehaviour.OnAudioFilterRead(float[], int)

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Parameters

data An array of floats comprising the audio data.
channels An int that stores the number of channels of audio data passed to this delegate.

Description

If OnAudioFilterRead is implemented, Unity will insert a custom filter into the audio DSP chain.

The filter is inserted in the same order as the MonoBehaviour script is shown in the inspector.

OnAudioFilterRead is called every time a chunk of audio is sent to the filter (this happens frequently, every ~20ms depending on the sample rate and platform). The audio data is an array of floats ranging from [-1.0f;1.0f] and contains audio from the previous filter in the chain or the AudioClip on the AudioSource. If this is the first filter in the chain and a clip isn't attached to the audio source, this filter will be played as the audio source. In this way you can use the filter as the audio clip, procedurally generating audio.

If there is more than one channel, the channel data is interleaved. This means each consecutive data sample in the array comes from a different channel until you run out of channels and loop back to the first. data.Length reports the total size of the data, so to find the number of samples per channel, divide data.Length by channels.

If OnAudioFilterRead is implemented a VU meter is shown in the inspector displaying the outgoing sample level. The process time of the filter is also measured and the spent milliseconds are shown next to the VU meter. The number turns red if the filter is taking up too much time, meaning the mixer will be starved of audio data.

Also note that OnAudioFilterRead is called on a different thread from the main thread (namely the audio thread) so calling into many Unity functions from this function is not allowed (if you try, a warning shows up at run time).

See Also: Audio Filters.

// This custom filter controls the gain by filtering the samples by multiplying each sample with a <i>gain</i> parameter.  

public var gain : float;

function OnAudioFilterRead(var data:float[], var channels:int) { for (var i = 0; i < data.Length; ++i) data[i] = data[i] * gain; }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961