Amplitude Logo

Code Examples


Include the Amplitude namespace at the top of your script before you can interact with Amplitude programmatically.

C#:

using CrazyMinnow.AmplitudeWebGL; // Import the Amplitude namespace so you can refer to the Amplitude class by name

Create a public Amplitude variable in your script:

C#:

public Amplitude amplitude;

Use GetComponent to get reference to an Amplitude instance just like you would any other component:

C#:

amplitude = GetComponent<Amplitude>();

Use the Amplitude.audioSource reference to control your AudioSource.

C#:

amplitude.audioSource.Play();

Use the Amplitude.audioSource.isPlaying to determine when you should be processing Amplitude.sample or Amplitude.average.

C#:


void Update()
{
	if (amplitude.audioSource.isPlaying)
	{
		// Access the amplitude average
		Debug.Log(amplitude.average);

		// Or access the sample array
		for (int i = 0; i < amplitude.sample.Length; i++)
		{
			Debug.Log(sample[i]);
		}
	}
}

AmplitudeTester.cs example script that links to Amplitude and a UI Slider and writes the Amplitude.average value to the UI Slider.

C#:


using UnityEngine;
using UnityEngine.UI; // Needed to display the amplitude data in a Unity UI Slider
using CrazyMinnow.AmplitudeWebGL; // Import the AmplitudeWebGL namespace

namespace CrazyMinnow.AmplitudeWebGL
{	
	public class AmplitudeTester : MonoBehaviour 
	{
		public Amplitude amplitude; // Reference to the Amplitude component
		public Slider uiSlider; // Reference to a Unity UI Slider component to display amplitude data

		// Read the amplitude sample or average values 
		// while the AudioSource AudioClip is playing
		void Update() 
		{
			// Only read Amplitude values when the AudioSource is playing
			if (amplitude.audioSource.isPlaying)
			{
				// Access the amplitude average
				uiSlider.value = amplitude.average;

				// Or access the sample array
				// for (int i = 0; i < amplitude.sample.Length; i++)
				// {
				// 	uiSlider.value = sample[i];
				// }
			}
		}

		// Example method calls the AudioSource.Play method
		public void Play()
		{
			amplitude.audioSource.Play();
		}

		// Example method calls the AudioSource.Stop method
		public void Stop()
		{
			amplitude.audioSource.Stop();
		}
	}
}