# 6. Lip Sync from Text Timing Part of [[Facial Animation and Lip Sync]]. Previous: [[5. Lip Sync from Audio Amplitude]]. Next: [[7. Face Tests Quest Performance and Pitfalls]]. ## 6.1 When there's no audio Many lines have no voice-over: barks, placeholder dialogue before recording, text-only RPG lines, or a game that only voices the first line of each conversation. A still mouth next to a speech bubble looks broken, and random jaw flapping looks cheap. The middle ground is a **plausible viseme timeline made from the text**. It's not phonetics, but it moves the mouth with the words, closes the lips on "m" and "b", rounds them on "oo", and pauses at commas. ## 6.2 TextVisemes (pure C#) The rules: 1. Lower-case the line and walk it letter by letter, at `charsPerSecond` (14 by default, a relaxed reading pace). 2. **Digraphs** first: `th`→TH, `ch`/`sh`→CH, `oo`→OU, `ee`→IH. 3. Single letters map by mouth shape: `p b m`→PP, `f v`→FF, `t d`→DD, `k g c q x`→KK, `s z`→SS, `n l`→NN, vowels to `aa/E/ih/oh/ou`, and `h`→AA (an open breath). 4. Spaces add half a letter of time. `, ; :` add a 0.18 s rest (Sil), and `. ! ?` add 0.35 s. 5. **Repeats merge**: "ll" becomes one long NN key instead of two, so the mouth doesn't chatter. ```csharp using System; using System.Collections.Generic; /// <summary>The 15 visemes used by Meta's Oculus LipSync set; most face rigs can map to these.</summary> public enum Viseme { Sil, PP, FF, TH, DD, KK, CH, SS, NN, RR, AA, E, IH, OH, OU } public readonly struct VisemeKey { public VisemeKey(Viseme viseme, double start, double duration) { Viseme = viseme; Start = start; Duration = duration; } public Viseme Viseme { get; } public double Start { get; } public double Duration { get; } public double End => Start + Duration; } /// <summary> /// Rough text-to-viseme timing for lines with no voice-over: letters map to visemes with simple /// English digraph rules, timed at a reading speed, with pauses at punctuation. It is a /// believable mouth flap, not phonetics. Deterministic and testable. /// </summary> public static class TextVisemes { public static List<VisemeKey> Build(string text, float charsPerSecond = 14f, float commaPause = 0.18f, float stopPause = 0.35f) { var keys = new List<VisemeKey>(); if (string.IsNullOrEmpty(text) || charsPerSecond <= 0f) return keys; var t = 0.0; var step = 1.0 / charsPerSecond; var lower = text.ToLowerInvariant(); for (var i = 0; i < lower.Length; i++) { var c = lower[i]; var next = i + 1 < lower.Length ? lower[i + 1] : '\0'; if (c == ',' || c == ';' || c == ':') { Add(keys, Viseme.Sil, t, commaPause); t += commaPause; continue; } if (c == '.' || c == '!' || c == '?') { Add(keys, Viseme.Sil, t, stopPause); t += stopPause; continue; } if (char.IsWhiteSpace(c)) { t += step * 0.5; // a word gap is shorter than a letter continue; } if (!char.IsLetter(c)) continue; // Digraphs first: "th", "ch", "sh", "oo", "ee". Viseme v; if (c == 't' && next == 'h') { v = Viseme.TH; i++; } else if ((c == 'c' || c == 's') && next == 'h') { v = Viseme.CH; i++; } else if (c == 'o' && next == 'o') { v = Viseme.OU; i++; } else if (c == 'e' && next == 'e') { v = Viseme.IH; i++; } else v = ForLetter(c); Add(keys, v, t, step); t += step; } return keys; } public static Viseme ForLetter(char c) { switch (c) { case 'p': case 'b': case 'm': return Viseme.PP; case 'f': case 'v': return Viseme.FF; case 't': case 'd': return Viseme.DD; case 'k': case 'g': case 'c': case 'q': case 'x': return Viseme.KK; case 'j': return Viseme.CH; case 's': case 'z': return Viseme.SS; case 'n': case 'l': return Viseme.NN; case 'r': return Viseme.RR; case 'a': return Viseme.AA; case 'e': return Viseme.E; case 'i': case 'y': return Viseme.IH; case 'o': return Viseme.OH; case 'u': case 'w': return Viseme.OU; case 'h': return Viseme.AA; default: return Viseme.Sil; } } /// <summary>Finds the key active at time t (binary search). Returns false after the end.</summary> public static bool Sample(List<VisemeKey> keys, double t, out VisemeKey key) { key = default; if (keys == null || keys.Count == 0 || t < keys[0].Start || t >= keys[keys.Count - 1].End) return false; int lo = 0, hi = keys.Count - 1; while (lo < hi) { var mid = (lo + hi + 1) / 2; if (keys[mid].Start <= t) lo = mid; else hi = mid - 1; } key = keys[lo]; return t < key.End; } static void Add(List<VisemeKey> keys, Viseme v, double start, double duration) { // Merge repeats ("ll", "ss") into one longer key so the mouth doesn't chatter. if (keys.Count > 0) { var last = keys[keys.Count - 1]; if (last.Viseme == v && Math.Abs(last.End - start) < 1e-9) { keys[keys.Count - 1] = new VisemeKey(v, last.Start, last.Duration + duration); return; } } keys.Add(new VisemeKey(v, start, duration)); } } ``` For "Hello, the moon." at 10 chars/s, the result starts with AA (h), holds one 0.2 s NN for "ll", has a 0.18 s rest at the comma, then TH, OU for "oo", and ends with a 0.35 s rest. All of that is asserted in part 7. `Sample(keys, t)` binary-searches the active key, so a long monologue costs O(log n) per frame. > [!warning] English only > English spelling is a poor guide to sound ("though", "through", "tough"), and other languages need different letter rules. It's good enough for mouth flaps at gameplay distance, and it falls apart in close-ups. With [[Localization]], tune `charsPerSecond` per language (Japanese text needs a much lower rate per character) or switch to audio-driven sync for localized VO. ## 6.3 VisemeMap: visemes to your rig Each viseme is a small set of blendshape weights. The defaults build all 15 from ARKit-style shapes (`jawOpen`, `mouthClose`, `mouthFunnel`, `mouthPucker`, `mouthStretch*`, `tongueOut` …), so a rig with ARKit shapes works immediately. If your rig has **dedicated viseme shapes** (Character Creator, VRM `aa/ih/ou/ee/oh`, or Oculus-style `viseme_PP`), map each viseme to its own shape at 100 instead. ```csharp using System; using System.Collections.Generic; using UnityEngine; /// <summary>Maps each viseme to the blendshapes that shape it on this rig.</summary> [CreateAssetMenu(menuName = "Face/Viseme Map", fileName = "VisemeMap")] public sealed class VisemeMap : ScriptableObject { [Serializable] public struct Entry { public Viseme viseme; public ChannelWeight[] weights; } [Tooltip("Channel used for audio-amplitude lip sync when there are no visemes.")] public string jawChannel = "jawOpen"; [Range(0f, 100f)] public float jawMax = 70f; public Entry[] entries = { new Entry { viseme = Viseme.PP, weights = new[] { new ChannelWeight { channel = "mouthClose", weight = 80 }, new ChannelWeight { channel = "mouthPressLeft", weight = 40 }, new ChannelWeight { channel = "mouthPressRight", weight = 40 } } }, new Entry { viseme = Viseme.FF, weights = new[] { new ChannelWeight { channel = "mouthRollLower", weight = 60 }, new ChannelWeight { channel = "mouthUpperUpLeft", weight = 30 }, new ChannelWeight { channel = "mouthUpperUpRight", weight = 30 } } }, new Entry { viseme = Viseme.TH, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 15 }, new ChannelWeight { channel = "tongueOut", weight = 40 } } }, new Entry { viseme = Viseme.DD, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 20 } } }, new Entry { viseme = Viseme.KK, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 25 } } }, new Entry { viseme = Viseme.CH, weights = new[] { new ChannelWeight { channel = "mouthFunnel", weight = 50 }, new ChannelWeight { channel = "jawOpen", weight = 15 } } }, new Entry { viseme = Viseme.SS, weights = new[] { new ChannelWeight { channel = "mouthStretchLeft", weight = 40 }, new ChannelWeight { channel = "mouthStretchRight", weight = 40 }, new ChannelWeight { channel = "jawOpen", weight = 8 } } }, new Entry { viseme = Viseme.NN, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 15 } } }, new Entry { viseme = Viseme.RR, weights = new[] { new ChannelWeight { channel = "mouthFunnel", weight = 30 }, new ChannelWeight { channel = "jawOpen", weight = 15 } } }, new Entry { viseme = Viseme.AA, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 60 } } }, new Entry { viseme = Viseme.E, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 35 }, new ChannelWeight { channel = "mouthStretchLeft", weight = 30 }, new ChannelWeight { channel = "mouthStretchRight", weight = 30 } } }, new Entry { viseme = Viseme.IH, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 20 }, new ChannelWeight { channel = "mouthSmileLeft", weight = 20 }, new ChannelWeight { channel = "mouthSmileRight", weight = 20 } } }, new Entry { viseme = Viseme.OH, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 45 }, new ChannelWeight { channel = "mouthFunnel", weight = 50 } } }, new Entry { viseme = Viseme.OU, weights = new[] { new ChannelWeight { channel = "jawOpen", weight = 20 }, new ChannelWeight { channel = "mouthPucker", weight = 80 } } }, }; public ChannelWeight[] WeightsFor(Viseme v) { foreach (var e in entries) { if (e.viseme == v) return e.weights; } return Array.Empty<ChannelWeight>(); } /// <summary>Every channel any viseme uses, so the mouth layer can clear them all.</summary> public IEnumerable<string> AllChannels() { var seen = new HashSet<string> { jawChannel }; yield return jawChannel; foreach (var e in entries) foreach (var w in e.weights) if (seen.Add(w.channel)) yield return w.channel; } } ``` Create one with **Create → Face → Viseme Map**. `AllChannels()` lists every channel any viseme uses. `LipSync` registers all of them, so it can ease each one back to 0 when the next viseme doesn't use it. > [!tip] Tuning the map > Play a line with `SpeakText` and watch three things. **PP** must fully close the lips (raise `mouthClose`, add `mouthPress`). **OU** must visibly round (push `mouthPucker`). **AA** sets the overall loudness of the mouth. Everything else can be subtle. Most of the perceived quality is in those three. ## 6.4 Using it `InkFaceDirector` calls `SpeakText(line.Text)` for any speaker line without a `#voice` clip. Two useful extras: - `LipSync.TextDuration` is the line's length in seconds. Use it to auto-advance unvoiced dialogue, or to set a typewriter speed so the text and the mouth finish together. - Text and typewriter: if your dialogue UI types text out ([[4. Story Loop and UI Toolkit Presenter]]), set the typewriter's characters per second to the same `charsPerSecond`, and the mouth will move with the letters appearing. ## 6.5 Better accuracy: bake phonemes offline For voiced hero lines in close-up, neither loudness nor spelling is enough. The usual pipeline is: 1. Run each VO file through an **offline phoneme or mouth-shape tool**. For example, the open-source **Rhubarb Lip Sync** outputs timed mouth shapes from audio, optionally guided by the transcript. Commercial middleware and some character-creation tools also export viseme tracks. 2. Import the result (often JSON or TSV of time→shape) as a `List<VisemeKey>`, using the same struct this series uses. 3. Play it through the **text path**: set `_timeline` from the baked keys instead of `TextVisemes.Build`. That's one more public method on `LipSync`. Write it as an exercise. > [!note] Not verified > Tool names are mentioned as examples only. Their current versions, licences, Unity integrations and output formats weren't checked for this note. Meta's older Oculus LipSync Unity plugin did real-time viseme detection on Quest; check its current support status before you rely on it. ## Exercises 1. Add `LipSync.SpeakBaked(List<VisemeKey> keys, AudioClip clip)` that plays the clip **and** follows the baked timeline (6.5). 2. Combine both sources: drive the mouth *shape* from text visemes and the jaw *amount* from audio loudness. That's a solid mid-tier for voiced NPCs without baking.