Below is my code, and I mainly want to create some clips with different pitches and store them in a list.
public class AudioClipPitchCreating : MonoBehaviour
{
public AudioClip originalClip;
public static List<AudioClip> AudioList = new List<AudioClip>();
public float[] pitchLevels = {1, 1.2f, 1.4f,1.6f,1.8f,2f }; // different pitch version
public AudioSource playMusic;
int i = 0;
void Awake()
{
playMusic.clip = originalClip;
foreach (var pitch in pitchLevels)
{
AudioClip modifiedClip = AdjustPitch(originalClip, pitch);
AudioList.Add(modifiedClip);
}
playMusic.Play();
}
AudioClip AdjustPitch(AudioClip clip, float pitch)
{
int samples = Mathf.CeilToInt(clip.samples / pitch);
float[] data = new float[samples * clip.channels];
clip.GetData(data, 0);
float[] newData = new float[samples * clip.channels];
for (int i = 0; i < samples; i++)
{
float sampleIndex = i * pitch;
int index0 = Mathf.FloorToInt(sampleIndex);
int index1 = Mathf.Min(index0 + 1, data.Length - 1);
float t = sampleIndex - index0;
newData[i] = Mathf.Lerp(data[index0], data[index1], t);
}
AudioClip newClip = AudioClip.Create("ModifiedClip", samples, clip.channels, clip.frequency, false);
newClip.SetData(newData, 0);
return newClip;
}
void Update()
{
if (Input.GetMouseButtonUp(0))
{
if (i == 4)
{
i = 0;
}
playMusic.clip = AudioList[i];
playMusic.time = 10f;
playMusic.Play();
i++;
}
}
}
I have dragged the clip onto originalClip
in the Unity editor. The clip creation works fine on the Windows etc platforms, but when I use WebGL. None of the clips has been created and I get the error below:
“Length of created clip must be larger than 0.”
I don’t understand why the length is not greater than 0 in WebGL when it works fine on other platforms.
Does anyone have an idea about this?
Thank you!