Building a clip from numbers
This page uses AudioClip from Unity. The glossary says what each one is.
Sometimes the sound has to live inside your DLL instead of a loose file, or your code makes the sound. FromPcm and FromPcm16 build a clip from a list of numbers. Each number is one point on the sound wave, called a sample.
Sounds builds clips from sample numbers
Call FromPcm or FromPcm16 with your samples to build a clip, then play it with PlayClip or PlayClipAt. Destroy the clip when you are finished with it.
public static class Sounds
{
public static AudioClip FromPcm(string name, float[] samples, int channels, int rate);
public static AudioClip FromPcm16(string name, short[] samples, int channels, int rate);
}
| Method | Returns | What it does |
|---|---|---|
FromPcm(name, samples, channels, rate) | AudioClip | Builds a clip from decimal samples between -1 and 1. |
FromPcm16(name, samples, channels, rate) | AudioClip | Builds a clip from 16-bit whole-number samples. |
Things to know
samplesholds the sound one moment at a time. For stereo sound, each moment is a left sample followed by a right sample. (The samples are interleaved frames.)channelsis 1 to 8, andrateis how many moments there are each second, from 8000 to 192000. The number of samples must be more than zero and a whole multiple ofchannels.FromPcmuses decimal samples between -1 and 1, andFromPcm16uses whole numbers from -32768 to 32767.FromPcmleaves your array alone. It works on a copy, turns a sample that is not a real number into silence, and clamps any other sample into the range -1 to 1.FromPcm16divides each sample by 32768, so -32768 becomes -1.- You own the clip you get back, so destroy it when you are finished. The framework does not keep a reference to it. Pass it to
UnityEngine.Object.Destroywhen you no longer need it. - Play the clip with
PlayCliporPlayClipAt.Effectsis the usual channel for sound effects.
Limits
- Big arrays are refused. The limit is the same 16 MiB that
LoadWavuses, counted in bytes: about 4.2 millionfloatvalues, or about 8.4 millionshortvalues. A bigger array givesnulland one line in the log. - Wrong arguments throw an error that names the argument. A
nullor emptynamethrowsArgumentException. AnullsamplesthrowsArgumentNullException. A badchannels,rateor sample count throwsArgumentException. - Call these from your mod’s normal code. From a background thread you started, Unity refuses to build the clip and you get
null. See Main thread. - You get
nullwhen Unity can’t build the clip, and the first failure is written to the log.