synth

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 12 Imported by: 1 module, 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 generates typed PCM sources.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ADSR

type ADSR struct {
	Attack  time.Duration
	Decay   time.Duration
	Sustain float64
	Release time.Duration
}

ADSR describes a linear attack, decay, sustain, and release volume envelope.

func NewADSR

func NewADSR(attack, decay time.Duration, sustain float64, release time.Duration) (ADSR, error)

NewADSR validates and returns an ADSR envelope.

func (ADSR) NewState

func (a ADSR) NewState(rateHz int) (EnvelopeState, error)

NewState converts each stage duration to whole frames, rounding down.

type Control

type Control interface {
	// contains filtered or unexported methods
}

Control is a synth-owned command. Pass the concrete commands by value.

Example
package main

import (
	"github.com/BeatGlow/audio"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.FloatPCM,
			Bits: 64,
		},
	}
	voice, err := (synth.Sine[float64]{}).NewVoice(format)
	if err != nil {
		panic(err)
	}
	if err := voice.Schedule(synth.TriggerAt(
		0,
		synth.Pitch{
			Kind:  synth.PitchHz,
			Value: 2000,
		},
		0.5,
		0,
	)); err != nil {
		panic(err)
	}

	// Queue the control by value on the voice's output timeline.
	var cut synth.Control = synth.Cut{}
	if err := voice.Schedule(synth.VoiceEvent{
		Frame:   2,
		Control: cut,
	}); err != nil {
		panic(err)
	}
	dst := audio.Buffer[float64]{{0, 0, 0, 0}}
	if n, err := voice.ReadFrames(dst); err != nil || n != 4 || dst[0][1] <= 0 || dst[0][3] != 0 {
		panic("expected sound before the cut and silence after it")
	}

}

type Cut

type Cut struct{}

Cut stops the current note immediately.

type Envelope

type Envelope interface {
	// NewState creates modulation state for one voice at rateHz.
	NewState(rateHz int) (EnvelopeState, error)
}

Envelope configures independently initialized modulation for each voice.

Example
package main

import (
	"github.com/BeatGlow/audio/synth"
)

func main() {
	var envelope synth.Envelope = synth.ADSR{Sustain: 0.5}
	first, err := envelope.NewState(48000)
	if err != nil {
		panic(err)
	}
	second, err := envelope.NewState(48000)
	if err != nil {
		panic(err)
	}

	// Evaluating one note leaves the other state idle.
	first.NoteOn(0)
	var active, idle [1]float64
	first.FillValues(0, active[:])
	second.FillValues(0, idle[:])
	if active[0] != 0.5 || idle[0] != 0 {
		panic("expected independent envelope states")
	}

}

type EnvelopeLoop

type EnvelopeLoop struct {
	StartTick int
	EndTick   int
}

EnvelopeLoop is an inclusive range on the envelope's tick timeline.

type EnvelopePoint

type EnvelopePoint struct {
	Tick  int
	Value float64
}

EnvelopePoint is a value at a zero-based envelope tick.

type EnvelopeState

type EnvelopeState interface {
	// NoteOn starts modulation at frame.
	NoteOn(frame int64)
	// NoteOff starts release at frame.
	NoteOff(frame int64)
	// FillValues writes one value per frame, starting at firstFrame.
	FillValues(firstFrame int64, dst []float64)
}

EnvelopeState evaluates a note's modulation in voice-local output frames.

Example
package main

import (
	"time"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	envelope := synth.ADSR{
		Attack:  time.Second,
		Sustain: 1,
	}
	state, err := envelope.NewState(4)
	if err != nil {
		panic(err)
	}

	// Fill a window on the voice's output timeline, starting at frame 10.
	state.NoteOn(10)
	var levels [3]float64
	state.FillValues(10, levels[:])
	if levels != [3]float64{0, 0.25, 0.5} {
		panic("expected a linear attack")
	}

}

type FM

type FM[T audio.Sample] struct {
	CarrierRatio    float64
	ModulatorRatio  float64
	ModulationIndex float64
	Envelope        Envelope
}

FM is a two-operator sine instrument. The modulator adds phase to the carrier in radians. Both operators run at a ratio of the triggered pitch.

func (FM[T]) NewVoice

func (f FM[T]) NewVoice(format audio.Format) (Voice[T], error)

NewVoice creates an idle FM voice with mono or front-stereo output. The ratios must be finite and positive, and the modulation index must be finite and nonnegative. Both operator frequencies must stay below Nyquist. With a nil envelope, Release stops the voice immediately.

type Fade

type Fade struct{ Frames int64 }

Fade fades out the current note over a positive number of output frames.

type FiniteEnvelopeState

type FiniteEnvelopeState interface {
	EnvelopeState
	Finished(frame int64) bool
}

FiniteEnvelopeState reports when a released volume envelope can be retired. It reports whether the voice can stop before rendering the given frame.

Example
package main

import (
	"time"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	state, err := (synth.ADSR{
		Sustain: 1,
		Release: time.Second,
	}).NewState(4)
	if err != nil {
		panic(err)
	}
	state.NoteOn(0)
	state.NoteOff(2)

	// A released ADSR can report when the voice can be retired.
	finite, ok := state.(synth.FiniteEnvelopeState)
	if !ok || finite.Finished(5) || !finite.Finished(6) {
		panic("expected a four-frame release")
	}

}

type Instrument

type Instrument[T audio.Sample] interface {
	NewVoice(format audio.Format) (Voice[T], error)
}

Instrument defines a reusable sound. Each new voice has independent playback state.

Example

NewVoice gives each note its own playback state.

package main

import (
	"github.com/BeatGlow/audio"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	var instrument synth.Instrument[float64] = synth.Sine[float64]{}
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.FloatPCM,
			Bits: 64,
		},
	}
	first, err := instrument.NewVoice(format)
	if err != nil {
		panic(err)
	}
	second, err := instrument.NewVoice(format)
	if err != nil {
		panic(err)
	}
	if err := first.Schedule(synth.TriggerAt(
		0,
		synth.Pitch{
			Kind:  synth.PitchHz,
			Value: 2000,
		},
		0.5,
		0,
	)); err != nil {
		panic(err)
	}
	frames := audio.Buffer[float64]{{0, 0}}
	n, err := first.ReadFrames(frames)
	if err != nil || n != 2 || frames[0][1] <= 0 || !first.Active() || second.Active() {
		panic("expected an audible note in the first voice only")
	}

}

type LoopMode

type LoopMode uint8

LoopMode determines how a sample cursor moves at the end of a loop. With LoopPingPongExclusiveEnd, linear interpolation holds the last sample through the upper turn.

const (
	LoopForward              LoopMode = iota // Wrap to the start at the end.
	LoopPingPong                             // Reverse direction at the endpoints.
	LoopPingPongExclusiveEnd                 // Reflect at the exclusive end.
)

type Note

type Note struct {
	Duration    time.Duration
	FrequencyHz float64
	Gain        float64
}

Note plays a pitch in Hertz at a linear gain in [0, 1]. Zero frequency and gain describe a rest. Notes that span no output frames are skipped.

func Silence

func Silence(duration time.Duration) Note

Silence advances a track without interrupting its release tail.

type OPL2

type OPL2[T audio.Sample] struct{}

OPL2 is a register-driven, nine-channel melodic OPL2 instrument. A voice represents one chip and duplicates its mono output in stereo.

func (OPL2[T]) NewVoice

func (OPL2[T]) NewVoice(format audio.Format) (Voice[T], error)

NewVoice creates a chip using the requested output rate. Trigger starts its clock and sets the output gain. Pitch and key state come from OPLWrite.

type OPLWrite

type OPLWrite struct {
	Address, Value uint8
}

OPLWrite writes a chip register on the voice's output-frame timeline.

type PCMFileOptions

type PCMFileOptions struct {
	RootHz                               float64
	Envelope, PanEnvelope, PitchEnvelope Envelope
	Loop, SustainLoop                    *SampleLoop
}

PCMFileOptions sets the root tuning, envelopes, and optional source-frame loops of a decoded PCM clip.

type PCMFilter

type PCMFilter struct {
	Cutoff, Resonance, Envelope uint8
}

PCMFilter sets the Impulse Tracker resonant low-pass filter on a PCM voice.

type PCMFirstPass

type PCMFirstPass struct{ EndSourceFrame int64 }

PCMFirstPass sets the exclusive source end of a PCM trigger's first pass. Schedule it immediately after Trigger at the same frame. A configured loop takes over at that boundary.

type PCMInstrument

type PCMInstrument[T, Stored audio.Sample] struct {
	// contains filtered or unexported fields
}

PCMInstrument is a reusable mono or front-stereo clip.

func LoadPCMInstrument

func LoadPCMInstrument[T audio.Sample](
	ctx context.Context, path string, options PCMFileOptions,
) (instrument *PCMInstrument[T, float64], err error)

LoadPCMInstrument decodes a mono or front-stereo audio file into a reusable PCM instrument. It loads the entire clip into memory and closes the file and decoder before returning. A nil context returns audio.ErrNilContext.

func NewPCMInstrument

func NewPCMInstrument[T, Stored audio.Sample](
	config PCMInstrumentConfig[Stored],
) (*PCMInstrument[T, Stored], error)

NewPCMInstrument validates and copies a clip into normalized PCM.

func (*PCMInstrument[T, Stored]) NewVoice

func (i *PCMInstrument[T, Stored]) NewVoice(format audio.Format) (Voice[T], error)

NewVoice allocates independent playback and envelope state. Returned PCM voices implement TickVoice. Stereo clips are averaged for mono output.

func (*PCMInstrument[T, Stored]) SwapTrackerClipAt

func (i *PCMInstrument[T, Stored]) SwapTrackerClipAt(frame int64, held bool) VoiceEvent

SwapTrackerClipAt starts this clip at source frame zero on an active Impulse Tracker WAV voice. It preserves the voice's gain ramp, filter history, and envelopes. Held selects the sustain loop when the clip provides one.

type PCMInstrumentConfig

type PCMInstrumentConfig[Stored audio.Sample] struct {
	Samples       audio.Buffer[Stored]
	Format        audio.Format
	RootHz        float64
	Envelope      Envelope
	PanEnvelope   Envelope
	PanLaw        PCMPanLaw
	PitchEnvelope Envelope
	Loop          *SampleLoop
	SustainLoop   *SampleLoop
	Mixer         PCMMixer
	TrackerMono   bool
}

PCMInstrumentConfig describes a pitched PCM clip. Envelope controls volume, PanEnvelope adds to the channel pan, and PitchEnvelope offsets pitch in semitones. A nil volume envelope releases the voice immediately.

type PCMMixer

type PCMMixer uint8

PCMMixer selects interpolation and stereo gain behavior for a PCM clip. PCMImpulseTracker uses cubic interpolation, linear panning, and inverted output polarity to reproduce the Impulse Tracker WAV driver.

const (
	PCMLinear         PCMMixer = iota // Linear interpolation and separate stereo attenuation.
	PCMImpulseTracker                 // Impulse Tracker WAV mixer.
)

type PCMPanLaw

type PCMPanLaw uint8

PCMPanLaw determines the left and right gains of stereo PCM output.

const (
	PCMLinearBalance PCMPanLaw = iota // Keep the favored channel at unity gain.
	PCMSquareRootPan                  // Distribute constant power across both channels.
)

type PCMSurround

type PCMSurround struct {
	Enabled bool
}

PCMSurround reverses the phase of the right channel of a PCM voice.

type PCMTrackerCut

type PCMTrackerCut struct{}

PCMTrackerCut ramps the tail of an Impulse Tracker PCM voice for the remainder of the current tracker tick.

type PCMTrackerResetMix

type PCMTrackerResetMix struct{}

PCMTrackerResetMix resets the WAV voice's gain ramp and filter history while preserving the clip and its current playback position.

type Pitch

type Pitch struct {
	Kind  PitchKind
	Value float64
}

Pitch is a frequency in Hertz or a step in source frames per output frame.

type PitchKind

type PitchKind uint8

PitchKind identifies the units of a pitch value.

const (
	PitchHz         PitchKind = iota + 1 // Frequency in Hertz.
	PitchSampleStep                      // Source frames per output frame.
)

type PointEnvelope

type PointEnvelope struct {
	Points  []EnvelopePoint
	Sustain *EnvelopeLoop
	Loop    *EnvelopeLoop
}

PointEnvelope describes a curve interpolated between points on a tick timeline. Each tick's value is held across its output frames.

func (PointEnvelope) NewState

func (e PointEnvelope) NewState(rateHz int) (EnvelopeState, error)

NewState snapshots the points and loops. Sustain takes precedence while the note is held. A normal loop remains enabled after release.

type Release

type Release struct{}

Release releases the current note.

type Retrigger

type Retrigger struct {
	OffsetSourceFrame int64
	ResetEnvelope     bool
}

Retrigger restarts a sound while preserving its pitch and gain.

type SampleLoop

type SampleLoop struct {
	StartFrame int64
	EndFrame   int64
	Mode       LoopMode
}

SampleLoop describes a half-open range of source frames.

type Sequencer

type Sequencer[T audio.Sample] struct {
	// contains filtered or unexported fields
}

Sequencer renders a fixed-duration mix of tracks that share a frame origin.

func NewSequencer

func NewSequencer[T audio.Sample](
	format audio.Format, duration time.Duration, tracks ...Track[T],
) (*Sequencer[T], error)

NewSequencer opens one voice per track. Note boundaries and the exclusive score end are rounded down from cumulative durations at the output rate. Notes extending past the score end are truncated. Include any desired release tail in duration.

func (*Sequencer[T]) PCMFormat

func (s *Sequencer[T]) PCMFormat() audio.Format

PCMFormat returns the format used by all voices and the rendered mix.

func (*Sequencer[T]) ReadFrames

func (s *Sequencer[T]) ReadFrames(dst audio.Buffer[T]) (int, error)

ReadFrames fills the caller's planes up to the exclusive score end. The final read may return PCM together with io.EOF. A voice error terminates the score after any blocks already delivered by this call.

type SetGain

type SetGain struct{ Gain float64 }

SetGain sets the voice's linear gain independently of its envelope.

type SetPan

type SetPan struct{ Pan float64 }

SetPan places the voice between -1 (left) and +1 (right), with zero centered.

type SetPitch

type SetPitch struct{ Pitch Pitch }

SetPitch changes the pitch without resetting the phase or sample cursor. A zero sample step holds the cursor of a PCM voice.

type Sine

type Sine[T audio.Sample] struct{}

Sine is a reusable sine instrument. Its zero value is ready to use.

func (Sine[T]) NewVoice

func (Sine[T]) NewVoice(format audio.Format) (Voice[T], error)

NewVoice creates an idle voice with mono or front-left/front-right output. The voice accepts representable Hertz pitches below Nyquist, linear gain in [0, 1], and zero source offsets. Panning attenuates the opposite stereo channel linearly and has no effect in mono. Release is immediate because the sine voice has no envelope. Retrigger resets phase and preserves any fade in progress.

type TickEnvelopeState

type TickEnvelopeState interface {
	EnvelopeState
	// AdvanceTick advances modulation for the half-open interval [firstFrame, endFrame).
	AdvanceTick(firstFrame, endFrame int64)
}

TickEnvelopeState receives each tick after its first-frame note controls.

Example
package main

import (
	"github.com/BeatGlow/audio/synth"
)

func main() {
	envelope := synth.PointEnvelope{
		Points: []synth.EnvelopePoint{
			{
				Tick:  0,
				Value: 0.5,
			},
			{
				Tick:  1,
				Value: 0.25,
			},
		},
	}
	state, err := envelope.NewState(48000)
	if err != nil {
		panic(err)
	}
	ticked, ok := state.(synth.TickEnvelopeState)
	if !ok {
		panic("expected a tick-based envelope")
	}

	// Start the note before advancing its first tick.
	ticked.NoteOn(0)
	ticked.AdvanceTick(0, 2)
	var levels [4]float64
	ticked.FillValues(0, levels[:2])
	ticked.AdvanceTick(2, 4)
	ticked.FillValues(2, levels[2:])
	if levels != [4]float64{0.5, 0.5, 0.25, 0.25} {
		panic("expected each tick to hold its level")
	}

}

type TickVoice

type TickVoice[T audio.Sample] interface {
	Voice[T]
	ScheduleTick(firstFrame, endFrame int64) error
}

TickVoice accepts voice-local tick intervals with an exclusive end.

Example
package main

import (
	"github.com/BeatGlow/audio"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.FloatPCM,
			Bits: 64,
		},
	}
	instrument, err := synth.NewPCMInstrument[float64](synth.PCMInstrumentConfig[float64]{
		Samples: audio.Buffer[float64]{{1, 1, 1, 1}},
		Format:  format,
		RootHz:  440,
		Envelope: synth.PointEnvelope{
			Points: []synth.EnvelopePoint{
				{
					Tick:  0,
					Value: 0.5,
				},
				{
					Tick:  1,
					Value: 0.25,
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}
	voice, err := instrument.NewVoice(format)
	if err != nil {
		panic(err)
	}
	ticked, ok := voice.(synth.TickVoice[float64])
	if !ok {
		panic("expected a voice with tick scheduling")
	}
	if err := ticked.Schedule(synth.TriggerAt(
		0,
		synth.Pitch{
			Kind:  synth.PitchSampleStep,
			Value: 1,
		},
		1,
		0,
	)); err != nil {
		panic(err)
	}

	// Schedule consecutive half-open ticks on the voice's output timeline.
	for start := int64(0); start < 4; start += 2 {
		if err := ticked.ScheduleTick(start, start+2); err != nil {
			panic(err)
		}
	}
	var frames [4]float64
	if n, err := ticked.ReadFrames(audio.Buffer[float64]{frames[:]}); err != nil || n != 4 ||
		frames != [4]float64{0.5, 0.5, 0.25, 0.25} {
		panic("expected a separate level for each tick")
	}

}

type Tone

type Tone[T audio.Sample] struct {
	// contains filtered or unexported fields
}

Tone generates an indefinite mono sine wave.

func NewTone

func NewTone[T audio.Sample](format audio.Format, hz, gain float64) (*Tone[T], error)

NewTone creates a mono source at hz and linear gain in [0, 1].

func (*Tone[T]) PCMFormat

func (t *Tone[T]) PCMFormat() audio.Format

PCMFormat reports the configured tone format.

func (*Tone[T]) ReadFrames

func (t *Tone[T]) ReadFrames(dst audio.Buffer[T]) (int, error)

ReadFrames fills the caller's mono plane, maintaining phase across reads.

func (*Tone[T]) SeekFrame

func (t *Tone[T]) SeekFrame(frame int64) error

SeekFrame restores the phase at a zero-based output frame.

func (*Tone[T]) SeekTime

func (t *Tone[T]) SeekTime(at time.Duration) (time.Duration, error)

SeekTime sets the same phase the oscillator would have reached by rendering from time zero to the corresponding frame.

type Track

type Track[T audio.Sample] struct {
	Instrument Instrument[T]
	Notes      []Note
}

Track plays notes in order on one voice of its instrument.

type Trigger

type Trigger struct {
	Pitch             Pitch
	Gain              float64
	OffsetSourceFrame int64
}

Trigger starts a note at the given pitch, gain, and zero-based source offset.

type Voice

type Voice[T audio.Sample] interface {
	audio.Source[T]

	// Schedule validates and queues an event. Events at the same frame run in
	// scheduling order, before that frame is rendered.
	Schedule(event VoiceEvent) error

	// Active reports whether a note is playing or finishing its tail.
	// A queued future trigger does not make an idle voice active.
	Active() bool
}

Voice renders PCM and accepts controls on its own output-frame timeline. Callers serialize reads, scheduling, and activity checks.

Example
package main

import (
	"github.com/BeatGlow/audio"

	"github.com/BeatGlow/audio/synth"
)

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.FloatPCM,
			Bits: 64,
		},
	}
	voice, err := (synth.Sine[float64]{}).NewVoice(format)
	if err != nil {
		panic(err)
	}
	if err := voice.Schedule(synth.TriggerAt(
		2,
		synth.Pitch{
			Kind:  synth.PitchHz,
			Value: 2000,
		},
		0.5,
		0,
	)); err != nil {
		panic(err)
	}

	// The queued trigger leaves the first two frames silent.
	dst := audio.Buffer[float64]{{0, 0, 0, 0}}
	if n, err := voice.ReadFrames(dst); err != nil || n != 4 ||
		dst[0][0] != 0 || dst[0][1] != 0 || dst[0][3] <= 0 {
		panic("expected the note to start at frame two")
	}

}

type VoiceEvent

type VoiceEvent struct {
	Frame   int64
	Control Control
}

VoiceEvent applies a control at a zero-based output frame.

func CutAt

func CutAt(frame int64) VoiceEvent

CutAt constructs a timed Cut.

func FadeAt

func FadeAt(frame, frames int64) VoiceEvent

FadeAt constructs a timed Fade.

func ReleaseAt

func ReleaseAt(frame int64) VoiceEvent

ReleaseAt constructs a timed Release.

func RetriggerAt

func RetriggerAt(frame int64, offsetSourceFrame int64, resetEnvelope bool) VoiceEvent

RetriggerAt constructs a timed Retrigger.

func SetGainAt

func SetGainAt(frame int64, gain float64) VoiceEvent

SetGainAt constructs a timed SetGain.

func SetPanAt

func SetPanAt(frame int64, pan float64) VoiceEvent

SetPanAt constructs a timed SetPan.

func SetPitchAt

func SetPitchAt(frame int64, pitch Pitch) VoiceEvent

SetPitchAt constructs a timed SetPitch.

func TriggerAt

func TriggerAt(frame int64, pitch Pitch, gain float64, offsetSourceFrame int64) VoiceEvent

TriggerAt constructs a timed Trigger.

Directories

Path Synopsis
internal
opl2
Package opl2 renders the melodic mode of the Yamaha YM3812.
Package opl2 renders the melodic mode of the Yamaha YM3812.

Jump to

Keyboard shortcuts

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