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

描述

使用剪辑中的样本数据填充数组。

样本为浮点值,范围为 -1.0f 到 1.0f。样本数由 float 数组的长度决定。 使用 offsetSamples 参数开始从剪辑中的特定位置读取。如果从偏移开始的读取长度大于剪辑长度,则读取将环绕, 即从剪辑的开头读取剩余的样本。

注意,对于压缩音频文件,仅当在音频导入器中将 Load Type 设置为 Decompress on Load 时才能检索样本数据。否则,将返回所有样本值均为零的数组。

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); } }