I have created a custom audio generator and want to play it through FMOD in Unity on Windows. However whenever I access a Monobehaviour from PCMReadCallback Unity freezes. So far I’ve worked out that the callback is run on a different thread (I’m assuming a thread spawned by FMOD for audio processing) and I’m guessing due to Unity’s lack of multithreading support this is causing issues. How can I get around this and get data from another object into the FMOD callback from an external generator?
Although I’m not sure it will fix all your issues I’ve spotted a common flaw in your code.
exinfo.pcmreadcallback = pcmreadcallback;
is short hand for
var cb = new SOUND_PCMREADCALLBACK(pcmreadcallback);
exinfo.pcmreadcallback = cb;
and now you’ve passed a reference to FMOD of a managed object that is only in the local scope and will garbage collected some time after your FMODStreamPlayer.CreateStream method has finished.
You need initialise a SOUND_PCMREADCALLBACK (and also a SOUND_PCMSETPOSCALLBACK) class member variable that will stay around while FMOD is still issuing the callback.
This seemed to be causing the issue. Its working now and I can reference other components from the callback. There is still an issue with Unity sometimes crashing when I stop the editor however.
Be very conservative in what managed objects you access. Try not to allocate any managed objects.