Version: 2022.2
LanguageEnglish
  • C#

AudioClip.GetData

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Switch to Manual

Declaration

public bool GetData(float[] data, int offsetSamples);

Description

Fills an array with sample data from the clip.

The samples are floats ranging from -1.0f to 1.0f. The sample count is determined by the length of the float array. Use the offsetSamples parameter to start the read from a specific position in the clip. If the read length from the offset is longer than the clip length, the read will wrap around and read the remaining samples from the start of the clip.

Note: For compressed audio files, you can retrieve the sample data only when Load Type is set to Decompress on Load in the audio importer. GetData doesn't work with streamed audio clips, including clips streamed from the disk and clips created with AudioClip.Create where the stream parameter has been set to true. If GetData can't read the data, the input array fills with zeroes, the console logs an error, and GetData returns false.

using UnityEngine;

public class Example : MonoBehaviour { // Read all the samples from the clip, reducing their gain by half // as we go along.

void Start() { AudioSource audioSource = GetComponent<AudioSource>(); float[] samples = new float[audioSource.clip.samples * audioSource.clip.channels]; audioSource.clip.GetData(samples, 0);

for (int i = 0; i < samples.Length; ++i) { samples[i] = samples[i] * 0.5f; }

audioSource.clip.SetData(samples, 0); } }

WebGL: The sample data of audio clips is loaded asynchronously in the WebGL platform. This makes it necessary to check the loadState of an AudioClip before reading the sample data.

using UnityEngine;
using UnityEngine.Audio;
using System.Collections;

public class ExampleGetDataCoroutine : MonoBehaviour { void Start() { StartCoroutine(GetAudioData()); }

IEnumerator GetAudioData() { AudioSource audioSource = GetComponent<AudioSource>(); // Wait for sample data to be loaded while (audioSource.clip.loadState != AudioDataLoadState.Loaded) { yield return null; }

// Read all the samples from the clip, reducing their gain by half // as we go along. float[] samples = new float[audioSource.clip.samples * audioSource.clip.channels]; audioSource.clip.GetData(samples, 0);

for (int i = 0; i < samples.Length; ++i) { samples[i] = samples[i] * 0.5f; }

audioSource.clip.SetData(samples, 0); } }