Documentation
¶
Overview ¶
Package synth generates typed PCM sources.
Index ¶
- type ADSR
- type Control
- type Cut
- type Envelope
- type EnvelopeLoop
- type EnvelopePoint
- type EnvelopeState
- type FM
- type Fade
- type FiniteEnvelopeState
- type Instrument
- type LoopMode
- type Note
- type OPL2
- type OPLWrite
- type PCMFileOptions
- type PCMFilter
- type PCMFirstPass
- type PCMInstrument
- type PCMInstrumentConfig
- type PCMMixer
- type PCMPanLaw
- type PCMSurround
- type PCMTrackerCut
- type PCMTrackerResetMix
- type Pitch
- type PitchKind
- type PointEnvelope
- type Release
- type Retrigger
- type SampleLoop
- type Sequencer
- type SetGain
- type SetPan
- type SetPitch
- type Sine
- type TickEnvelopeState
- type TickVoice
- type Tone
- type Track
- type Trigger
- type Voice
- type VoiceEvent
- func CutAt(frame int64) VoiceEvent
- func FadeAt(frame, frames int64) VoiceEvent
- func ReleaseAt(frame int64) VoiceEvent
- func RetriggerAt(frame int64, offsetSourceFrame int64, resetEnvelope bool) VoiceEvent
- func SetGainAt(frame int64, gain float64) VoiceEvent
- func SetPanAt(frame int64, pan float64) VoiceEvent
- func SetPitchAt(frame int64, pitch Pitch) VoiceEvent
- func TriggerAt(frame int64, pitch Pitch, gain float64, offsetSourceFrame int64) VoiceEvent
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ADSR ¶
ADSR describes a linear attack, decay, sustain, and release volume envelope.
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")
}
}
Output:
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")
}
}
Output:
type EnvelopeLoop ¶
EnvelopeLoop is an inclusive range on the envelope's tick timeline.
type EnvelopePoint ¶
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")
}
}
Output:
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.
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")
}
}
Output:
type Instrument ¶
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")
}
}
Output:
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.
type Note ¶
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.
type OPL2 ¶
OPL2 is a register-driven, nine-channel melodic OPL2 instrument. A voice represents one chip and duplicates its mono output in stereo.
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 ¶
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.
type PCMPanLaw ¶
type PCMPanLaw uint8
PCMPanLaw determines the left and right gains of stereo PCM output.
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 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 SampleLoop ¶
SampleLoop describes a half-open range of source frames.
type Sequencer ¶
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 ¶
PCMFormat returns the format used by all voices and the rendered mix.
func (*Sequencer[T]) ReadFrames ¶
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 ¶
Sine is a reusable sine instrument. Its zero value is ready to use.
func (Sine[T]) NewVoice ¶
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")
}
}
Output:
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")
}
}
Output:
type Tone ¶
Tone generates an indefinite mono sine wave.
func (*Tone[T]) ReadFrames ¶
ReadFrames fills the caller's mono plane, maintaining phase across reads.
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 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")
}
}
Output:
type VoiceEvent ¶
VoiceEvent applies a control at a zero-based output frame.
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.