クリップからサンプルデータの配列を取得します。
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); } }