Documentation
¶
Overview ¶
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.
A Stream is an endless io.Reader for an audio player; Stream.Render serves offline rendering. Notes arrive through the voice.Sink methods from any goroutine and start at the next render block of BlockFrames frames.
Index ¶
- Constants
- Variables
- type Envelope
- type Filter
- type FilterType
- type Format
- type Glide
- type Patch
- type Reverb
- type Sample
- type SampleLoader
- type Stream
- func (s *Stream) Format() Format
- func (s *Stream) NoteOff(owner voice.Owner, inst voice.Instrument, note float32)
- func (s *Stream) NoteOn(owner voice.Owner, inst voice.Instrument, note, velocity, pan float32)
- func (s *Stream) Read(p []byte) (int, error)
- func (s *Stream) Release(owner voice.Owner)
- func (s *Stream) Render(left, right []float32)
- func (s *Stream) SampleRate() int
- func (s *Stream) SetGain(gain float32)
- func (s *Stream) SetPatch(owner voice.Owner, inst voice.Instrument, p Patch) error
- func (s *Stream) SetReverb(r Reverb) error
- func (s *Stream) SetVoice(owner voice.Owner, v *voice.Voice, load SampleLoader) error
- type StreamConfig
- type Vibrato
- type Waveform
Constants ¶
const ( MaxLayers = 4 MaxUnison = 7 )
The limits of Patch.Layers and Patch.Unison.
const ( MinSampleRate = 16000 MaxSampleRate = 192000 DefaultVoices = 32 // BlockFrames is the render block. Sink calls are applied at the start // of a block, and glide and vibrato are updated once per block. BlockFrames = 64 )
The limits of StreamConfig.
const MinEnvelopeTime = 2 * time.Millisecond
MinEnvelopeTime is the shortest attack, release (and, when the sustain is below 1, decay) an Envelope gets. Shorter values are raised to it, so a note never starts or stops with a click.
const StealFade = MinEnvelopeTime
StealFade is how long a stolen voice fades out before the new note starts on it. Cutting a sounding voice to zero at once would click.
Variables ¶
var DefaultReverb = Reverb{Size: 0.75, Damping: 0.4, Width: 1}
DefaultReverb is the reverb a new stream has: a medium hall.
var FilterTypes = [...]string{"lowpass", "highpass", "bandpass"}
FilterTypes lists the names of the filter types, indexed by FilterType: "lowpass", "highpass", "bandpass".
Functions ¶
This section is empty.
Types ¶
type Envelope ¶
type Envelope struct {
Attack time.Duration
Decay time.Duration
Sustain float32 // 0 to 1
Release time.Duration
}
Envelope is a linear attack, decay, sustain, release envelope. Attack rises from 0 to 1, decay falls to Sustain, the level holds until the note is released, and release falls to 0. A Sustain of 0 ends the note after the decay without a note off, which suits short blips.
type Filter ¶
type Filter struct {
Type FilterType
Cutoff float32
Resonance float32
}
Filter is a resonant state-variable filter, a low-pass unless Type says otherwise. Cutoff is in hertz (0 turns the filter off; values above 45 % of the sample rate are lowered to it); Resonance is 0 (none) to just below 1 (strong peak at the cutoff).
type FilterType ¶
type FilterType uint8
FilterType selects the output of the Filter.
const ( LowPass FilterType = iota // keeps what is below the cutoff HighPass // keeps what is above the cutoff (hi-hats, shakers) BandPass // keeps a band around the cutoff (snares, claps) )
The filter types. All three come from the same state-variable filter, so they cost the same.
func (FilterType) String ¶
func (t FilterType) String() string
String returns the filter type's name.
type Glide ¶
Glide slides the pitch into the note: it starts From semitones away from the note (negative is below) and reaches it linearly after Time. A zero Time turns it off.
type Patch ¶
type Patch struct {
Wave Waveform
// PulseWidth is the high part of a Square's cycle, 0.01 to 0.99; 0 means 0.5.
PulseWidth float32
// Detune adds a second oscillator of the same wave this many semitones
// away, mixed half and half; 0 means a single oscillator.
Detune float32
// Sample replaces the oscillator when set. The stream keeps the pointer:
// do not change the sample after handing it over.
Sample *Sample
Env Envelope
Glide Glide
Vibrato Vibrato
Filter Filter
// Gain scales the patch's output; 0 means 1.
Gain float32
// Reverb is how much of the patch goes into the stream's reverb, 0 (dry)
// to 1. See Stream.SetReverb.
Reverb float32
// Layers are semitone offsets played together for every note, like a
// chord: [0, -12, 7] plays the note, an octave below and a fifth above.
// Each layer takes a voice of the pool, and the velocity is scaled by
// 1/sqrt(len) so a chord is about as loud as one note. Empty means [0];
// at most MaxLayers, each -24 to 24.
Layers []float32
// Unison runs this many copies of the oscillator, detuned evenly across
// Spread semitones (in total), for the sound of a section instead of a
// single instrument. 0 and 1 mean one oscillator; at most MaxUnison.
// Oscillator patches only.
Unison int
Spread float32
}
Patch is one instrument sound: an oscillator (Wave, PulseWidth, Detune) or, when Sample is set, sample playback, followed by the filter, the envelope and the gain. Glide and Vibrato modulate the pitch of either.
The zero values of PulseWidth and Gain mean their defaults (0.5 and 1), so a zero Patch is a plain sine with the shortest envelope.
func PatchFromSpec ¶
func PatchFromSpec(spec voice.InstrumentSpec, load SampleLoader) (Patch, error)
PatchFromSpec turns an instrument of a voice file into a patch. A spec with a Sample needs load (nil returns an error for it). The result is validated.
type Reverb ¶
type Reverb struct {
Size float32 // room size: decay from short (0) to very long (1)
Damping float32 // how fast high frequencies die out
Width float32 // stereo width of the reverb's output: 0 mono, 1 full
}
Reverb sets the stream's reverb, a room every patch can send into with its Patch.Reverb level. All fields are 0 to 1.
type Sample ¶
type Sample struct {
Data []float32 // mono samples, -1 to 1
Rate int // sample rate of Data in hertz
Root float32 // the note (MIDI numbering) Data sounds at
Loop bool
// LoopStart and LoopEnd are frame indexes; LoopEnd 0 means len(Data).
LoopStart, LoopEnd int
}
Sample is a mono recording played by a Patch. It plays at its own pitch when the note equals Root and is resampled with linear interpolation for other notes. A one-shot sample ends the note at its end (with a fade over the last MinEnvelopeTime, so a sample that stops abruptly does not click); a looped one repeats LoopStart to LoopEnd until the envelope ends.
type SampleLoader ¶
SampleLoader resolves the sample name of a voice file's instrument (for example a path relative to the voice file) to a sample. It may return the same *Sample for the same name; samples are never modified.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is the synthesizer: an endless PCM source for an audio player and a voice.Sink for the notes.
Threading: Read and Render belong to one goroutine at a time (the audio player's); they own the voices. NoteOn, NoteOff, Release, SetPatch and SetGain may be called from any goroutine: they append a command to a mutex-guarded buffer that the renderer swaps for its own at the start of every block of BlockFrames frames. Nothing is dropped, and once the buffers have grown to the busiest block they no longer allocate.
func NewStream ¶
func NewStream(cfg StreamConfig) (*Stream, error)
NewStream returns a silent stream with no patches. It reports every problem of cfg together.
func (*Stream) NoteOn ¶
NoteOn implements voice.Sink. A note for an instrument without a patch is ignored. Velocity is clamped to 0 to 1, pan to -1 to 1.
func (*Stream) Read ¶
Read fills p with whole frames in the stream's format and returns the number of bytes written; it never ends and never returns an error. A p shorter than one frame reads nothing. Read and Render must not run concurrently. Steady state allocates nothing.
func (*Stream) Render ¶
Render fills left and right (which must have the same length) with the next frames, -1 to 1, for offline rendering. It continues where Read left off. Steady state allocates nothing.
func (*Stream) SampleRate ¶
SampleRate returns the stream's sample rate in hertz.
func (*Stream) SetGain ¶
SetGain sets the master gain (1 by default) applied before the output is clipped to -1 to 1. Safe from any goroutine.
func (*Stream) SetPatch ¶
SetPatch sets the patch that instrument inst of owner plays. Notes already sounding keep their old patch. It returns the patch's validation errors (and sets nothing) when p is invalid, or an error for an out-of-range inst. The patch is copied; its Sample is shared and must not change. Safe from any goroutine; allocates.
func (*Stream) SetReverb ¶
SetReverb sets the stream's reverb (DefaultReverb at first). Patches send into it with Patch.Reverb. It returns an error, and changes nothing, for a field outside 0 to 1. Safe from any goroutine.
func (*Stream) SetVoice ¶
SetVoice sets the patches of all instruments of owner from v: the five voice instruments and its percussion sounds (see PatchFromSpec and Stream.SetPatch). Percussion slots v does not use keep their patches. It reports the errors of every instrument together and sets nothing if any fails. Safe from any goroutine; allocates.
type StreamConfig ¶
type StreamConfig struct {
SampleRate int // MinSampleRate to MaxSampleRate, required
Format Format // byte format of Read; FormatFloat32 by default
Voices int // size of the voice pool; 0 means DefaultVoices
}
StreamConfig configures a Stream.
type Vibrato ¶
Vibrato modulates the pitch with a sine of Rate hertz and Depth semitones (peak), starting Delay after the note on. A zero Rate or Depth turns it off.