Programmable Sounds in Unity


(trung) #1

Hi,
I’m having issue getting programmable sound to work in Unity with FMOD. I tried to create the FMOD sound from audioclip but it alway failed. I have provided the full source code for my test below.
Thanks!

Source code:
FMOD.Sound CreateSoundFromAudioClip(AudioClip clip, string name)
{
float[] samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);

        FMOD.System lowlevel = FMODUnity.RuntimeManager.LowlevelSystem;

        uint lenbytes = (uint)(clip.samples * clip.channels * sizeof(float));

        FMOD.CREATESOUNDEXINFO soundinfo = new FMOD.CREATESOUNDEXINFO();
        soundinfo.length = lenbytes;
        soundinfo.format = FMOD.SOUND_FORMAT.PCMFLOAT;
        soundinfo.defaultfrequency = clip.frequency;
        soundinfo.numchannels = clip.channels;

        FMOD.RESULT result;
        FMOD.Sound sound;
        result = lowlevel.createSound("", FMOD.MODE.OPENUSER, ref soundinfo, out sound);

        IntPtr ptr1, ptr2;
        uint len1, len2;
        result = sound.@lock(0, lenbytes, out ptr1, out ptr2, out len1, out len2);
        Marshal.Copy(samples, 0, ptr1, (int)(len1 / sizeof(float)));
        if (len2 > 0)
        {
            Marshal.Copy(samples, (int)(len1 / sizeof(float)), ptr2, (int)(len2 / sizeof(float)));
        }
        result = sound.unlock(ptr1, ptr2, len1, len2);

        result = sound.setMode(FMOD.MODE.LOOP_NORMAL);

        result = lowlevel.playSound(sound, channelGroup, false, out channel);

        return sound;
    }

It’s return error: ArgumentNullException: Argument cannot be null.Parameter name: dest
Marshal.Copy(samples, 0, ptr1, (int)(len1 / sizeof(float)));


(Cameron Baron) #2

You also need to provide the soundinfo.cbsize
soundinfo.cbsize = Marshal.SizeOf(soundinfo);

You should be checking the FMOD.Result after getting them back from a function, createSound is returning ‘invalid parameter’.

The log file, fmod.log, which is created next to the assets folder (also found in the menu FMOD>Log Viewer) can sometimes contain more information on these errors.