# 5. Lip Sync from Audio Amplitude
Part of [[Facial Animation and Lip Sync]]. Previous: [[4. Blinks Gaze and Idle Life]]. Next: [[6. Lip Sync from Text Timing]].
## 5.1 The cheapest lip sync that works
Open the jaw when the voice is loud and close it when it's quiet. That's it. It reads as "talking" at any distance beyond a close-up, it works for **every language** and every actor, it needs **no preprocessing**, and it works for procedural or streamed audio. Many shipped games use exactly this for NPCs and save phoneme-accurate lip sync for hero close-ups (part 6).
What it can't do: shapes. "oo" and "ee" both just open the jaw, and closed-lip sounds (m, b, p) don't close the lips. Hide that with distance, a bit of expression, and fast attack.
## 5.2 Reading the voice's loudness
`AudioSource.GetOutputData(float[] samples, int channel)` fills a pre-allocated array with a short history window of the source's most recent output. The 6000.x Scripting Reference (checked 2026-12-01) says:
- The array length **must be a power of 2**. 256 samples at 48 kHz is about 5 ms, plenty for a jaw.
- Unity only starts recording that history **the first time you call it** on each source, so the first few frames return silence.
- It's meant for analysis, **not** low-latency processing. That's fine for a jaw.
- Use this non-allocating overload. The `float[] GetOutputData(int, int)` overload is deprecated because it allocates every call.
**RMS** (root mean square) turns those samples into one loudness number:
$\text{rms} = \sqrt{\tfrac{1}{N}\sum x_i^2}$
## 5.3 AmplitudeEnvelope (pure C#)
Raw RMS jitters every frame. The envelope does three things:
1. **Noise gate**: below `Gate` (0.02), the target is 0. Breaths and room tone don't flap the jaw.
2. **Gain**: `(rms − gate) × 6`, clamped to 1. Tune it per actor, because a whisper track needs more gain.
3. **Attack and release**: an exponential approach with a fast **attack** (40 ms) and a slower **release** (120 ms). The jaw snaps open on a syllable and relaxes between them instead of buzzing.
```csharp
using System;
/// <summary>
/// Turns a loudness signal (RMS 0..1) into a smooth mouth-open value 0..1 with a noise gate,
/// gain, and separate attack/release times so the jaw snaps open on syllables and relaxes between them.
/// </summary>
public sealed class AmplitudeEnvelope
{
public float Gate { get; set; } = 0.02f;
public float Gain { get; set; } = 6f;
public float AttackSeconds { get; set; } = 0.04f;
public float ReleaseSeconds { get; set; } = 0.12f;
public float Value { get; private set; }
public float Step(float rms, float dt)
{
var target = rms <= Gate ? 0f : Math.Min(1f, (rms - Gate) * Gain);
var tau = target > Value ? AttackSeconds : ReleaseSeconds;
var k = tau <= 0f ? 1f : 1f - (float)Math.Exp(-dt / tau);
Value += (target - Value) * k;
return Value;
}
public static float Rms(float[] samples, int count)
{
if (count <= 0)
return 0f;
double sum = 0;
for (var i = 0; i < count; i++)
sum += samples[i] * samples[i];
return (float)Math.Sqrt(sum / count);
}
}
```
The tests (part 7) check the shape: after 100 ms of a loud signal the value is above 0.85, and after 100 ms of silence it's still between 0.25 and 0.5, because the release is slower than the attack.
## 5.4 The LipSync component
One component handles both sources (audio here, text in part 6) and owns the **visemes** layer:
- `SpeakAudio(clip)` plays the clip on the voice `AudioSource` and drives `jawChannel` up to `jawMax` from the envelope.
- `SpeakText(line)` builds a viseme timeline (part 6).
- Every mouth channel **eases toward its target** with a 50 ms time constant, so shapes blend instead of snapping.
- The layer's **weight fades** to 1 while talking and back to 0 between lines (150 ms), so the expression's mouth (a smile) shows through when the character is quiet.
```csharp
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Writes the FaceRig viseme layer from one of two sources:
/// - Audio: RMS of the voice AudioSource's output drives the jaw (any language, no preprocessing).
/// - Text: a TextVisemes timeline for the line drives full mouth shapes (no audio needed).
/// Between lines the layer weight fades to 0 so the expression shows through.
/// </summary>
[RequireComponent(typeof(FaceRig))]
public sealed class LipSync : MonoBehaviour
{
public enum Source { None, Audio, Text }
[SerializeField] VisemeMap visemeMap;
[SerializeField] AudioSource voice;
[SerializeField] int sampleWindow = 256;
[SerializeField] float charsPerSecond = 14f;
[SerializeField, Min(0.01f)] float visemeBlendSeconds = 0.05f;
[SerializeField, Min(0.01f)] float layerFadeSeconds = 0.15f;
FaceRig _rig;
readonly AmplitudeEnvelope _envelope = new AmplitudeEnvelope();
float[] _samples;
List<VisemeKey> _timeline;
double _timelineStart;
int _jaw;
readonly Dictionary<string, int> _ids = new Dictionary<string, int>();
readonly Dictionary<int, float> _targets = new Dictionary<int, float>();
readonly Dictionary<int, float> _current = new Dictionary<int, float>();
readonly List<int> _scratch = new List<int>();
public Source Active { get; private set; }
public bool IsTalking => Active != Source.None;
void Start()
{
_rig = GetComponent<FaceRig>();
// GetOutputData requires a power-of-two length.
_samples = new float[Mathf.ClosestPowerOfTwo(Mathf.Max(64, sampleWindow))];
foreach (var name in visemeMap.AllChannels())
{
var id = _rig.Channel(name);
_ids[name] = id;
_current[id] = 0f;
}
_jaw = _ids[visemeMap.jawChannel];
_rig.Visemes.Weight = 0f;
}
/// <summary>Plays a voice clip and lip-syncs to its loudness.</summary>
public void SpeakAudio(AudioClip clip)
{
if (clip == null || voice == null)
return;
voice.clip = clip;
voice.Play();
Active = Source.Audio;
}
/// <summary>Mouths a line of text with no audio (barks, unvoiced dialogue, placeholder VO).</summary>
public void SpeakText(string line)
{
_timeline = TextVisemes.Build(line, charsPerSecond);
_timelineStart = Time.timeAsDouble;
Active = _timeline.Count > 0 ? Source.Text : Source.None;
}
public void Stop()
{
if (voice != null && Active == Source.Audio)
voice.Stop();
Active = Source.None;
}
/// <summary>Seconds a text line will take; useful to auto-advance dialogue.</summary>
public float TextDuration => _timeline != null && _timeline.Count > 0 ? (float)_timeline[_timeline.Count - 1].End : 0f;
void Update()
{
_targets.Clear();
switch (Active)
{
case Source.Audio:
if (!voice.isPlaying)
{
Active = Source.None;
break;
}
voice.GetOutputData(_samples, 0);
var open = _envelope.Step(AmplitudeEnvelope.Rms(_samples, _samples.Length), Time.deltaTime);
_targets[_jaw] = open * visemeMap.jawMax;
break;
case Source.Text:
if (TextVisemes.Sample(_timeline, Time.timeAsDouble - _timelineStart, out var key))
{
foreach (var w in visemeMap.WeightsFor(key.Viseme))
if (_ids.TryGetValue(w.channel, out var id))
_targets[id] = w.weight;
}
else if (Time.timeAsDouble - _timelineStart >= TextDuration)
{
Active = Source.None;
}
break;
}
// Ease every mouth channel toward its target (absent = 0) so visemes blend instead of snapping.
var k = 1f - Mathf.Exp(-Time.deltaTime / visemeBlendSeconds);
_scratch.Clear();
_scratch.AddRange(_current.Keys);
foreach (var id in _scratch)
{
_targets.TryGetValue(id, out var target);
var v = Mathf.Lerp(_current[id], target, k);
_current[id] = v;
_rig.Visemes.Set(id, v);
}
var layerTarget = IsTalking ? 1f : 0f;
_rig.Visemes.Weight = Mathf.MoveTowards(_rig.Visemes.Weight, layerTarget, Time.deltaTime / layerFadeSeconds);
}
}
```
Setup:
1. Add an `AudioSource` at the character's mouth: a child of the head bone, spatial blend 1, routed to your **Dialogue** mixer group ([[Audio Mixers and Character Audio]], [[1. 3D AudioSource Settings]]).
2. Add `LipSync` next to `FaceRig`, and assign the `AudioSource` and a `VisemeMap` (part 6; only its `jawChannel` and `jawMax` matter for audio).
3. Test with `SpeakAudio` from a context-menu method or from `InkFaceDirector`.
> [!warning] Check where in the chain the samples come from
> The Scripting Reference doesn't say whether the source's `volume` or its 3D attenuation is applied before `GetOutputData` sees the samples, and this series didn't test it. If either is applied first, a quiet or distant NPC will barely move its jaw. Before tuning, log the RMS of one clip at `volume` 1 and 0.3, and near and far from the listener. If the values change, normalise in the envelope (divide by `voice.volume`) or keep voice sources at volume 1 and balance levels in the mixer.
## 5.5 Tuning per voice
| Symptom | Fix |
|---|---|
| Jaw buzzes during long vowels | Raise `ReleaseSeconds` (0.15–0.2) |
| Jaw lags the words | Lower `AttackSeconds` (0.02–0.03), or delay the audio by one frame |
| Mouth never fully closes between words | Raise `Gate` |
| Quiet actor barely moves | Raise `Gain`. Better: normalise VO files at import |
| Shouting looks like yawning | Lower `jawMax` (50–60) |
Expose the envelope settings per actor if your cast varies a lot. An `AmplitudeEnvelope` is a plain class, so you can serialize its settings in a small `[Serializable]` struct and copy them in.
## Exercises
1. Add a second channel: drive `mouthFunnel` from the *ratio* of low to high frequency energy, using `GetSpectrumData`. It's a cheap "oo" detector. Measure whether it helps.
2. Make `LipSync` work for voice chat: feed it RMS from a microphone or Vivox stream instead of an `AudioSource` ([[Voice Chat with Vivox]]).