You have a delegate declared as:
public delegate void PCMReaderCallback(float[] data);
Then you have a Unity AudioClip.Create
function that uses this delegate as a parameter. This is the only thing to understand here.
This is what it looks like:
public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream, PCMReaderCallback pcmreadercallback);
As, you can see, it takes PCMReaderCallback
as parameter which is the name of the delegate above.
Now, in order to use it, you first have a to create a function that matches the parameter of the delegate. Remember that our delegate takes float[]
as a parameter and is a void
return type. It really doesn't matter what you name this function. It should look like something below:
void OnAudioRead(float[] data)
{
}
Finally, to use the function:
AudioClip newAudioClip = AudioClip.Create("Pigeon", samplerate * 2, 1, samplerate, true, OnAudioRead);
AudioSource attachedSource = GetComponent<AudioSource>();
attachedSource.clip = newAudioClip;
attachedSource.Play();
As, you can see, we passed in our OnAudioRead
function to the PCMReaderCallback pcmreadercallback
parameter which will call our OnAudioRead
function when each time AudioClip
reads data. This is automatically called by Unity.
My question is how would I use a delegate which has already been
defined to call on a method of my choice?
Let's use PCMReaderCallback
as an example. PCMReaderCallback
is declared in a class called AudioClip
. To use use it, you must use the full name AudioClip.PCMReaderCallback
.
Create a function that takes AudioClip.PCMReaderCallback
as parameter, do some data processing, then use Invoke
to call that function that is passed in when processing is done:
void makeAlecAudioFunction(AudioClip.PCMReaderCallback allecCallBack)
{
//Generate some random dummy audio data
float[] dummyData = new float[4000];
for (int i = 0; i < dummyData.Length; i++)
{
dummyData[i] = Random.Range(0f, 1f);
}
//Call the function that was passed in then pass it in the data we generated
allecCallBack.Invoke(dummyData);
}
Usage of that function:
Create a function that will be called when makeAlecAudioFunction
has finished processing data.
void OnAlecAudio(float[] data)
{
for (int i = 0; i < data.Length; i++)
{
Debug.Log("Alec Audio Data: " + data[i]);
}
}
Now, to call the makeAlecAudioFunction
function, call it and pass in the OnAlecAudio
function. Remember that their parameter must match!:
makeAlecAudioFunction(OnAlecAudio);
Finally, I think that the main reason behind callback functions is to do something without making the rest of the program wait, then perform a callback when that action is done. Because of this, your makeAlecAudioFunction
should be a coroutine function or should be called in another Thread
(complicated in Unity). If using Thread
, the callback must be called in the main Thread
. Just trying to keep this example simple.