Documentation
¶
Overview ¶
Package voice turns dialogue text into musical gibberish for games: text is split into phonemes of a fictional language, each phoneme plays a short blip, a quiet motif follows the punctuation, and the caller learns how much text to reveal at every moment.
The package knows nothing about time sources or audio devices. Notes go to a Sink; the built-in synthesizer in package synth implements it. See doc/guide.md for the user guide and doc/design.md for how it is built.
Index ¶
- Constants
- Variables
- func PercussionNames() []string
- func PresetNames() []string
- type BeatTrack
- type Category
- type Clock
- type ComposeOptions
- type Contour
- type Event
- type EventKind
- type FieldError
- type Instrument
- type InstrumentSpec
- type Language
- type Note
- type Owner
- type Percussion
- type Phoneme
- type PhonemeDef
- type PunctuationDef
- type Rest
- type Reveal
- type Rhythm
- type SayOptions
- type Sink
- type Speaker
- func (s *Speaker) Close()
- func (s *Speaker) Done() bool
- func (s *Speaker) Events() []Event
- func (s *Speaker) Pause()
- func (s *Speaker) Paused() bool
- func (s *Speaker) Resume()
- func (s *Speaker) Revealed() int
- func (s *Speaker) Say(v *Voice, text string, opts SayOptions)
- func (s *Speaker) Skip()
- func (s *Speaker) Stop()
- func (s *Speaker) Timeline() Timeline
- func (s *Speaker) Update(dt time.Duration)
- type Timeline
- type TokenKind
- type UnknownPolicy
- type Voice
Constants ¶
const ( DefaultBPM = 90 DefaultDivision = 4 DefaultBeatVolume = 0.8 DefaultPauseRest = RestBeat DefaultEndRest = RestBar )
The defaults of the optional rhythm fields.
const ( DefaultBaseNote = 64 DefaultVariation = 1 DefaultVelocity = 0.8 DefaultLength = 0.8 DefaultSpeed = 14 DefaultMotifVolume = 0.2 DefaultBreath = 0.4 )
The defaults of the optional voice file fields.
const InstPercussion = InstMotif + 1
InstPercussion is the instrument of a voice's first percussion sound: sound i of Voice.Percussion plays on InstPercussion + i.
const InstrumentCount = int(InstPercussion) + MaxPercussion
InstrumentCount is the number of instruments a Sink must handle per owner: the five voice instruments and MaxPercussion percussion sounds. Valid Instrument values are 0 to InstrumentCount-1.
const MaxPercussion = 8
MaxPercussion is the most percussion sounds a voice can have.
Variables ¶
var Filters = []string{"lowpass", "highpass", "bandpass"}
Filters lists the valid values of InstrumentSpec.Filter.
var Waves = []string{"sine", "triangle", "square", "saw", "noise"}
Waves lists the valid values of InstrumentSpec.Wave.
Functions ¶
func PercussionNames ¶
func PercussionNames() []string
PercussionNames returns the names of the built-in percussion sounds, sorted.
Types ¶
type BeatTrack ¶
BeatTrack is the pattern of one percussion sound: one character per step of a bar, 'x' a hit, '-' a ghost hit (half velocity), '.' a rest. It repeats every bar.
type Category ¶
type Category uint8
Category is the sound class of a phoneme. Each category plays on its own instrument of the voice: Category(c).Instrument() is InstVowel, InstSonorant, InstFricative or InstPlosive.
const ( Vowel Category = Category(InstVowel) Sonorant Category = Category(InstSonorant) Fricative Category = Category(InstFricative) Plosive Category = Category(InstPlosive) )
The phoneme categories, in the order of the matching instruments.
func (Category) Instrument ¶
func (c Category) Instrument() Instrument
Instrument returns the instrument that plays phonemes of category c.
type Clock ¶
type Clock struct {
BPM float32 // the music's tempo, 40 to 240
// Phase is the time from the start of the line until the music's next
// bar begins. It is taken modulo a bar, so the time since the music
// started, negated, works too.
Phase time.Duration
}
Clock ties a rhythmic line to music the game plays: the line takes the music's tempo and its first syllable lands on a bar line of the music.
type ComposeOptions ¶
type ComposeOptions struct {
// Clock ties the line to the game's music: its tempo replaces the
// voice's and the first syllable lands on the music's next bar line
// (after the count-in). Nil keeps the voice's own tempo and starts at
// once.
Clock *Clock
// MuteBeat leaves out the voice's percussion, for example when the
// game's music already has a beat.
MuteBeat bool
}
ComposeOptions tune how ComposeWith times a line of a voice with a Rhythm. They do nothing for a voice without one.
type Event ¶
Event is something that happened to the line with number Line (counted from 1 per speaker, one per Say).
type FieldError ¶
type FieldError struct {
// File is "language" or "voice".
File string
// Path is the JSON path of the value, as in the file.
Path string
// Message says what is wrong, for example "2 is outside 0 to 1".
Message string
}
FieldError is one validation error of a language or voice file: the JSON path of the value it is about (for example "instruments.vowel.sustain" or "phonemes[2].symbol") and what is wrong with it. LoadLanguage, LoadVoice and Voice.Validate join every FieldError they find with errors.Join, so a tool that shows errors next to the field unwraps the joined error (its Unwrap() []error method) or uses errors.As for the first one.
func (*FieldError) Error ¶
func (e *FieldError) Error() string
Error returns "voice: <file>: <path>: <message>".
type Instrument ¶
type Instrument uint8
Instrument selects one of a voice's instruments: one per phoneme category, the motif, and the voice's percussion sounds.
const ( InstVowel Instrument = iota // vowels InstSonorant // sonorants (m, n, l, r, ...) InstFricative // fricatives (s, f, h, ...) InstPlosive // plosives (p, t, k, ...) InstMotif // the quiet melody under a line )
The instruments of a voice.
func (Instrument) String ¶
func (i Instrument) String() string
String returns the instrument's name as used in voice files ("vowel", "sonorant", "fricative", "plosive", "motif"), "percussion(N)" for the percussion sounds, or "instrument(N)" for an out-of-range value.
type InstrumentSpec ¶
type InstrumentSpec struct {
Wave string `json:"wave,omitempty"` // sine, triangle, square, saw, noise
PulseWidth float32 `json:"pulseWidth,omitempty"`
Detune float32 `json:"detune,omitempty"`
AttackMs float32 `json:"attackMs,omitempty"`
DecayMs float32 `json:"decayMs,omitempty"`
Sustain float32 `json:"sustain,omitempty"`
ReleaseMs float32 `json:"releaseMs,omitempty"`
GlideFrom float32 `json:"glideFrom,omitempty"`
GlideMs float32 `json:"glideMs,omitempty"`
VibratoRate float32 `json:"vibratoRate,omitempty"`
VibratoDepth float32 `json:"vibratoDepth,omitempty"`
VibratoDelayMs float32 `json:"vibratoDelayMs,omitempty"`
Filter string `json:"filter,omitempty"` // lowpass (default), highpass, bandpass
Cutoff float32 `json:"cutoff,omitempty"`
Resonance float32 `json:"resonance,omitempty"`
Gain float32 `json:"gain,omitempty"`
Reverb float32 `json:"reverb,omitempty"` // send into the stream's reverb, 0 to 1
Layers []float32 `json:"layers,omitempty"` // semitone offsets played together, at most 4
Unison int `json:"unison,omitempty"` // oscillator copies, at most 7
Spread float32 `json:"spread,omitempty"` // total detune of the unison copies in semitones
// Sample names a sound file the caller resolves (for example a path in
// an fs.FS next to the voice file). Root is the note it sounds at.
Sample string `json:"sample,omitempty"`
Root float32 `json:"root,omitempty"`
Loop bool `json:"loop,omitempty"`
LoopStart int `json:"loopStart,omitempty"`
LoopEnd int `json:"loopEnd,omitempty"`
}
InstrumentSpec describes the sound of one instrument of a voice, as written in a voice file: an oscillator patch, or a sample reference when Sample is set. The synthesizer turns it into a patch (synth.PatchFromSpec); its guide section lists what each field does. Times are in milliseconds.
Zero values mean defaults: Wave "" is "sine", PulseWidth 0 is 0.5, Gain 0 is 1, Root 0 is 60.
type Language ¶
type Language struct {
// contains filtered or unexported fields
}
Language is a fictional language: the phonemes text is split into, the punctuation rules and what happens to characters it does not know. Load one with LoadLanguage or LoadLanguageFS, or use DefaultLanguage.
A Language is immutable after loading and safe to share between goroutines and speakers.
func DefaultLanguage ¶
func DefaultLanguage() *Language
DefaultLanguage returns the built-in language: Latin letters with common digraphs (sh, ch, th, ng, ai, ee, oo, ou, ck), the default punctuation, and unknown letters and digits played as "a". It is parsed once and shared; a Language is immutable.
func LoadLanguage ¶
LoadLanguage reads a *.lang.json file. Malformed JSON and unknown fields are reported on their own; otherwise every validation error is returned together (errors.Join), each with its JSON path.
func LoadLanguageFS ¶
LoadLanguageFS reads the *.lang.json file name from fsys, see LoadLanguage.
func (*Language) Phonemes ¶
func (l *Language) Phonemes() []PhonemeDef
Phonemes returns a copy of the language's phonemes.
func (*Language) Punctuation ¶
func (l *Language) Punctuation() []PunctuationDef
Punctuation returns a copy of the language's punctuation rules.
type Note ¶
type Note struct {
On, Off time.Duration // from the start of the line
Instrument Instrument
Note float32 // semitones, MIDI numbering
Velocity float32 // 0 to 1
Pan float32 // -1 to 1
}
Note is one note of a Timeline.
type Owner ¶
type Owner uint16
Owner identifies who plays a note, usually one speaker. A Sink keeps the notes of different owners apart, so stopping one line never touches another. Owners are small integers chosen by the caller.
type Percussion ¶
type Percussion struct {
Name string
Note float32 // the note every hit plays, 0 to 127
Spec InstrumentSpec
}
Percussion is one percussion sound of a voice: an instrument played at a fixed note by the voice's Rhythm beat. Sound i of Voice.Percussion plays on instrument InstPercussion + i.
func BuiltinPercussion ¶
func BuiltinPercussion(name string) (Percussion, bool)
BuiltinPercussion returns the built-in percussion sound name, or false for an unknown name.
type Phoneme ¶
type Phoneme struct {
Kind TokenKind
Symbol string // the language's symbol; for whitespace " ", for skips the text itself
Category Category // TokenPhoneme only
Pitch float32 // TokenPhoneme: semitones from the language
Length float32 // TokenPhoneme: slot in beats; TokenPause: pause in beats
Velocity float32 // TokenPhoneme: relative loudness
Contour Contour // TokenPause from punctuation: its clause end rule
Clause bool // TokenPause from punctuation: ends a clause
Start, End int // byte span in the text
}
Phoneme is one token of a parsed line. The spans of a line's tokens tile the text: each starts where the previous ended, the first at 0 and the last ending at len(text).
func AppendParse ¶
AppendParse appends the tokens of text to dst and returns the result.
Symbols are matched longest first and case-insensitively (Unicode simple case folding, no normalization: "é" written as e plus a combining accent is two characters). A run of whitespace is one pause. Letters and digits the language does not know follow its UnknownPolicy; any other unknown character, and invalid UTF-8, is skipped. Parse is pure and allocates only to grow dst.
type PhonemeDef ¶
type PhonemeDef struct {
Symbol string // one or more runes, matched case-insensitively
Category Category // which instrument plays it
Pitch float32 // semitones added to the voice's note
Length float32 // relative length of its slot, 1 is one beat
Velocity float32 // relative loudness, 0 to 1
}
PhonemeDef is one phoneme of a language.
type PunctuationDef ¶
type PunctuationDef struct {
Symbol string // one or more runes, matched case-insensitively
Pause float32 // silence in beats
Contour Contour // what it does to the end of its clause
}
PunctuationDef is one punctuation rule of a language.
type Rest ¶
type Rest uint8
Rest says where a rhythmic voice starts again after punctuation. Every rest but RestNone leaves at least one step of silence.
type Rhythm ¶
type Rhythm struct {
BPM float32 // beats per minute, 40 to 240
Division int // steps per beat: 2 (eighths), 3 (triplets) or 4 (sixteenths)
// Swing delays every odd step by this share of a step, 0 to 0.5.
Swing float32
// Accents is the accent strength, 0 to 1, of each step of a bar
// (4*Division values). Empty means beats 1 and 3 strong, 2 and 4
// medium, the steps between them none.
Accents []float32
// PauseRest is where the voice starts again after punctuation without
// a contour (a comma), EndRest after punctuation with one (a period,
// question or exclamation mark).
PauseRest, EndRest Rest
// CountIn is the number of bars of beat before the voice starts, 0 to 2.
CountIn int
// BeatVolume is the velocity of a percussion hit, 0 to 1.
BeatVolume float32
// Beat holds one pattern per percussion sound, sorted by sound name.
Beat []BeatTrack
}
Rhythm makes a voice speak on a beat grid, like a rapper: every syllable starts on a grid step, strong steps are accented, and an optional percussion pattern plays under the line. A bar has 4 beats of Division steps each. See the guide's rhythm section for how Compose uses it.
type SayOptions ¶
type SayOptions struct {
// Language splits the text; nil means DefaultLanguage().
Language *Language
// Speed scales playback: 2 is twice as fast. 0 means 1.
Speed float32
// Instant shows all text at once and plays the motif only.
Instant bool
// Clock and MuteBeat time a voice with a rhythm to the game's music;
// see [ComposeOptions]. While a Clock is set, Speed is ignored, so the
// line keeps the music's tempo.
Clock *Clock
MuteBeat bool
}
SayOptions tune one line of Speaker.Say.
type Sink ¶
type Sink interface {
// NoteOn starts note on instrument inst of owner.
NoteOn(owner Owner, inst Instrument, note float32, velocity float32, pan float32)
// NoteOff releases the sounding notes of owner on instrument inst that
// have this pitch. The instrument keeps a percussion hit from ending a
// motif note at the same pitch.
NoteOff(owner Owner, inst Instrument, note float32)
// Release releases every note of owner.
Release(owner Owner)
}
Sink receives the notes of a line. It is the seam between composing and sound: the built-in synthesizer (synth.Stream) implements it, a SoundFont backend or a recording test sink can too.
Notes are float semitones in MIDI numbering (60 is middle C), so pitch variation is not rounded. Velocity is 0 to 1, pan is -1 (left) to 1 (right).
Contract for implementations: the methods are called from the caller's goroutine (a game loop, a test), possibly while audio is being rendered on another goroutine; they must be safe for that, must not block for long and must not allocate in steady state. Every NoteOn is eventually matched by a NoteOff with the same owner, instrument and note, or by a Release of the owner.
type Speaker ¶
type Speaker struct {
// contains filtered or unexported fields
}
Speaker is the runtime that speaks lines: it plays a composed timeline on a Sink as time advances and tells the caller how much text to show.
Drive it from one goroutine: Say a line, call Update with the frame time every frame, show text[:Revealed()], and read Events. The reveal depends only on the accumulated time, not on how it was split into updates. Every note it starts is ended by a NoteOff or by Release(owner): Skip, Stop, Pause, Close and a Say over a running line release the owner's notes. Steady-state Update allocates nothing; Say allocates.
func NewSpeaker ¶
NewSpeaker returns a speaker that plays its notes on sink as owner. Use a different owner for every speaker of one sink.
func (*Speaker) Close ¶
func (s *Speaker) Close()
Close stops the running line like Stop and makes later Say calls do nothing. The speaker stays readable.
func (*Speaker) Done ¶
Done reports whether no line is playing (none started, or the last one completed, was skipped or stopped).
func (*Speaker) Events ¶
Events returns what happened since the previous Update began: events of Say, Skip, Stop and Close calls since then and of the Update itself. The slice is reused: it is valid until the next Update.
func (*Speaker) Pause ¶
func (s *Speaker) Pause()
Pause holds the line: time stops, and the sounding notes are released (a held note would hang). Resume continues with the next notes.
func (*Speaker) Revealed ¶
Revealed returns how many bytes of the line's text to show: text[:n] is always whole tokens (never half a UTF-8 character).
func (*Speaker) Say ¶
func (s *Speaker) Say(v *Voice, text string, opts SayOptions)
Say starts speaking text with voice v, replacing a running line (which is released and gets a Stopped event). It emits Started. A Say after Close does nothing.
func (*Speaker) Skip ¶
func (s *Speaker) Skip()
Skip ends the running line at once: all text is shown, its notes are released, and it emits Skipped. Without a running line it does nothing.
func (*Speaker) Stop ¶
func (s *Speaker) Stop()
Stop ends the running line where it is (the shown text stays as it is), releases its notes and emits Stopped.
func (*Speaker) Timeline ¶
Timeline returns the current line's timeline (empty before the first Say). Do not modify its slices.
type Timeline ¶
type Timeline struct {
Notes []Note
Reveals []Reveal
// Duration is when the line is over: the end of its last sound. A
// pause after the last phoneme (the final period) does not count.
Duration time.Duration
TextLen int
}
Timeline is a composed line: the notes to play and when to reveal how much text. Notes are sorted by On, Reveals by At (and Offset); the last reveal shows the whole text.
func Compose ¶
Compose turns the parsed tokens of text into a timeline for voice v; it is ComposeWith without options.
func ComposeText ¶
ComposeText parses text with lang and composes it with v; see Compose.
func ComposeWith ¶
func ComposeWith(v *Voice, text string, tokens []Phoneme, opts ComposeOptions) Timeline
ComposeWith turns the parsed tokens of text into a timeline for voice v. It is pure: the same voice, text, tokens and options always give the same timeline, because its randomness comes from a generator seeded with v.Seed xor a hash of the text.
Each phoneme gets a slot of Length beats (a beat is 1/v.Speed seconds) and a note on its category's instrument for v.Length of the slot, at v.BaseNote + v.Pitch + the phoneme's pitch + a random offset within v.Variation. Pauses add silence. The text of a token is revealed when it starts. The end of each clause follows its punctuation's contour, and when v.MotifVolume is above 0 a motif of two to four notes, one per clause, plays under the line. A voice with a Rhythm places its syllables on a beat grid instead and adds its percussion (see the guide's rhythm section). Out-of-range voice fields are clamped; beat patterns that do not fit the rhythm are left out.
type TokenKind ¶
type TokenKind uint8
TokenKind is what a Phoneme of a parsed line is.
const ( // TokenPhoneme sounds: a note on the instrument of its category. TokenPhoneme TokenKind = iota // TokenPause is silence: whitespace, punctuation, or an unknown letter // under UnknownPause. TokenPause // TokenSkip is revealed at once without sound or time: characters the // language does not know. TokenSkip )
type UnknownPolicy ¶
type UnknownPolicy uint8
UnknownPolicy says what happens to a letter or digit the language has no phoneme for. Other unknown characters (quotes, dashes, symbols, emoji) are always skipped: revealed at once, without sound or time.
const ( UnknownSkip UnknownPolicy = iota // revealed at once, no sound UnknownFallback // played as the fallback phoneme UnknownPause // a pause as long as a space )
func (UnknownPolicy) String ¶
func (p UnknownPolicy) String() string
String returns the policy's name as used in language files.
type Voice ¶
type Voice struct {
Name string
Language string // name the caller resolves; "" means DefaultLanguage
BaseNote float32 // the note a phoneme of pitch 0 plays, 24 to 108
Pitch float32 // semitones added to every note, -24 to 24
Variation float32 // random pitch spread in semitones (plus or minus), 0 to 12
Velocity float32 // loudness of the phonemes, 0 to 1
Length float32 // note length as a share of its slot, 0.05 to 1
Speed float32 // beats (phonemes of length 1) per second, 1 to 60
Pan float32 // -1 (left) to 1 (right)
// MotifVolume is the velocity of the motif notes, 0 to 1; 0 turns the
// motif off.
MotifVolume float32
// Breath is how long, in seconds, the motif's last note rings on after
// the voice's last sound, 0 to 2; the line ends after it. 0 ends the
// motif with the voice.
Breath float32
Seed uint64 // mixed with a hash of the text: same voice and text, same line
// Instruments are indexed by Instrument. Loading fills instruments the
// file leaves out with the vowel's.
Instruments [InstPercussion]InstrumentSpec
// Percussion are the sounds the rhythm's beat plays, sorted by name;
// sound i plays on instrument InstPercussion + i. At most
// MaxPercussion. Loading adds the built-in sounds the beat names but
// the file does not define.
Percussion []Percussion
// Rhythm puts the voice on a beat grid; nil speaks freely.
Rhythm *Rhythm
}
Voice is how one character speaks: the instruments, pitch, speed and variation. Load one with LoadVoice or LoadVoiceFS, or start from a Preset. Fields may be changed after loading (for example Pitch to tell two guards with the same voice apart); Voice.Validate checks them.
func LoadVoice ¶
LoadVoice reads a *.voice.json file. Malformed JSON and unknown fields are reported on their own; otherwise every validation error is returned together (errors.Join), each with its JSON path. Sample references are not resolved; that is the synthesizer's caller's job.
func LoadVoiceFS ¶
LoadVoiceFS reads the *.voice.json file name from fsys, see LoadVoice.
func Preset ¶
Preset returns a new copy of a starter voice: "soft", "chirpy", "gruff", "divine", "flow", "verse", "warrior", "robot", "ghost" or "elder" (see PresetNames). It returns an error for an unknown name.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
voiceplay
command
Command voiceplay renders the voice library's sounds to WAV files, so they can be heard without writing code.
|
Command voiceplay renders the voice library's sounds to WAV files, so they can be heard without writing code. |
|
Package dialogue loads and plays a conversation: a list of lines, each said by one speaker, each speaker with its own voice, with optional timing per line.
|
Package dialogue loads and plays a conversation: a list of lines, each said by one speaker, each speaker with its own voice, with optional timing per line. |
|
ebiten
module
|
|
|
Package synth is the built-in synthesizer of the voice library: oscillator and sample patches, a fixed voice pool, and a Stream that renders PCM and implements voice.Sink.
|
Package synth is the built-in synthesizer of the voice library: oscillator and sample patches, a fixed voice pool, and a Stream that renders PCM and implements voice.Sink. |
|
Package voicetest has test helpers for code that uses the voice library.
|
Package voicetest has test helpers for code that uses the voice library. |
|
Package wav reads 16-bit PCM WAV files into mono float32 samples and writes float32 stereo WAV files.
|
Package wav reads 16-bit PCM WAV files into mono float32 samples and writes float32 stereo WAV files. |