Passing Custom Data to the Audio Samplers (Unity Plugin)

From PopcornFX
Jump to navigation Jump to search
! IMPORTANT ! This is a PopcornFX v1 page. PopcornFX v2 Unity plugin documentation can be found here



Since v2.6 it's possible to pass custom data to the PopcornFX engine to be sampled via the spectrum samplers instead of Unity's audio listener's data.
This can be used to pass sound data from another source (external sound engine) or any arbitrary data to effects.

This is achieved by overriding PKFxManager's default callbacks with PKFxManager.SetDelegateOnAudioSpectrumData() and PKFxManager.SetDelegateOnAudioWaveformData().

Example Code

The following example script demonstrates how to replace the audio data with an arbitrary sinusoid oscillating with elapsed time.

using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using AOT;

public class testOverrideSpectrum : MonoBehaviour {

	private static float[] m_Samples;
	private static GCHandle m_SamplesHandle;
	private bool tmp;
	private static float offset = .25f;

	void Start () {
		// Initialize the data buffer. Expected size is 1024.
		m_Samples = new float[1024];
		// Pin the array
		m_SamplesHandle = GCHandle.Alloc(m_Samples, GCHandleType.Pinned);
		tmp = false;

	void Update()
		if (!tmp)
			PKFxManager.SetDelegateOnAudioSpectrumData(Marshal.GetFunctionPointerForDelegate(new Func<int, IntPtr, IntPtr>(OnAudioSpectrumData)));
		offset += Time.deltaTime;

	// MonoPInvokeCallback is required by IL2CPP (mostly for iOS' static libs)
	public static IntPtr OnAudioSpectrumData(int channel, IntPtr nbSamples)
		// Fill the buffer with the sine curve data.
		for (int x = 0; x < 1024; x++)
			m_Samples[x] = (Mathf.Sin(2f * Mathf.PI * ((x / 1024) - offset)) + 1f) / 2f / 100f;
		// return the address of the pinned object.
		return m_SamplesHandle.AddrOfPinnedObject();
	void OnDestroy()
		// Unpin the object to allow GC.