synth

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 8 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	MaxLayers = 4
	MaxUnison = 7
)

The limits of Patch.Layers and Patch.Unison.

View Source
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.

View Source
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.

View Source
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

View Source
var DefaultReverb = Reverb{Size: 0.75, Damping: 0.4, Width: 1}

DefaultReverb is the reverb a new stream has: a medium hall.

View Source
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 Format

type Format uint8

Format is the byte format Stream.Read produces.

const (
	// FormatFloat32 is interleaved stereo float32 little endian, 8 bytes a
	// frame (what Ebiten's NewPlayerF32 reads).
	FormatFloat32 Format = iota
	// FormatInt16 is interleaved stereo int16 little endian, 4 bytes a frame.
	FormatInt16
)

type Glide

type Glide struct {
	From float32
	Time time.Duration
}

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.

func (*Patch) Validate

func (p *Patch) Validate() error

Validate reports every problem of the patch together (errors.Join), or nil.

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

type SampleLoader func(name string) (*Sample, error)

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) Format

func (s *Stream) Format() Format

Format returns the byte format of Read.

func (*Stream) NoteOff

func (s *Stream) NoteOff(owner voice.Owner, inst voice.Instrument, note float32)

NoteOff implements voice.Sink.

func (*Stream) NoteOn

func (s *Stream) NoteOn(owner voice.Owner, inst voice.Instrument, note, velocity, pan float32)

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

func (s *Stream) Read(p []byte) (int, error)

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) Release

func (s *Stream) Release(owner voice.Owner)

Release implements voice.Sink.

func (*Stream) Render

func (s *Stream) Render(left, right []float32)

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

func (s *Stream) SampleRate() int

SampleRate returns the stream's sample rate in hertz.

func (*Stream) SetGain

func (s *Stream) SetGain(gain float32)

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

func (s *Stream) SetPatch(owner voice.Owner, inst voice.Instrument, p Patch) error

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

func (s *Stream) SetReverb(r Reverb) error

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

func (s *Stream) SetVoice(owner voice.Owner, v *voice.Voice, load SampleLoader) error

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

type Vibrato struct {
	Rate  float32
	Depth float32
	Delay time.Duration
}

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.

type Waveform

type Waveform uint8

Waveform is the shape of an oscillator.

const (
	Sine Waveform = iota
	Triangle
	Square
	Saw
	Noise
)

The oscillator waveforms. Square and Saw are band-limited with PolyBLEP; Noise is white noise and ignores the pitch (shape it with the filter).

func (Waveform) String

func (w Waveform) String() string

String returns the waveform's name ("sine", "triangle", "square", "saw", "noise").

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL