Documentation / Programming / Core

Core package

SynapSeq modulev4.43.1 Published Oct 18, 2026

Versioned API documentation and examples, mirrored from pkg.go.dev. Open the canonical package page

On this page

package core

Package core provides the application context and core functionality for the SynapSeq text-driven audio sequencer for brainwave entrainment.

Overview

This package is the public Go API for loading .spsq sequences, inspecting their metadata, rendering WAV output, streaming raw PCM, and producing JSON dumps.

Supported Format

SynapSeq currently supports text input in .spsq format.

Example Usage

package main

import (
    "context"
    "log"
    "os"
    "time"

    synapseq "github.com/synapseq-foundation/synapseq/v4/core"
)

func main() {
    // Create application context
    ctx := synapseq.NewAppContext()

    // Enable verbose output (optional)
    ctx = ctx.WithVerbose(os.Stderr, true)

// Load sequence (required before generating WAV or streaming)
loaded, err := ctx.LoadFile("input.spsq")
if err != nil {
    log.Fatal(err)
}

    // Generate WAV file
    if err := loaded.WAV("output.wav"); err != nil {
        log.Fatal(err)
    }

    // Or generate a JSON dump
    jsonDump, err := loaded.JSON()
    if err != nil {
        log.Fatal(err)
    }
    _ = jsonDump
}

File Paths

Input paths support:

Raw Content

Use LoadContent when the .spsq source is already available as a string, such as content received from a web form, embedded resource, or another in-memory source:

content := `
alpha
  tone 100 binaural 1 amplitude 1
00:00:00 alpha
00:01:00 alpha
`

loaded, err := ctx.LoadContent(content)
if err != nil {
log.Fatal(err)
}
_ = loaded

Output methods:

  • loaded.WAV("output.wav") writes a WAV file
  • loaded.Stream(writer) writes raw PCM to an io.Writer
  • loaded.JSON() returns JSON dump bytes

AI Generation

Use AppContext.AI to generate and validate an SPSQ sequence. The default provider uses an OpenAI-compatible chat completion API and requires SYNAPSEQ_AI_API_KEY. Model and API host default to gpt-4.1-mini and the OpenAI API; configure a local or alternate provider through AIOptions or the SYNAPSEQ_AI_MODEL and SYNAPSEQ_AI_BASE_URL environment variables. Provider defaults to AIProviderDefault. Set it to AIProviderAppleFoundation to use Apple's local Foundation Models through fmgo in darwin/arm64 builds; it requires macOS 27 or later, uses the system model by default, and does not require an API key or host. Other builds return an unsupported-provider error. Temperature applies only to the default provider. Set AIOptions.Timeout to a positive time.Duration appropriate for the calling application.

ctx := synapseq.NewAppContext()
loaded, err := ctx.AI(context.Background(), "Generate a 10 minute relaxation sequence", &synapseq.AIOptions{
    Model:   "local-model",
    BaseURL: "http://localhost:1234",
    Temperature: 1,
    Timeout: time.Minute,
})
if err != nil {
    log.Fatal(err)
}
content := loaded.RawContent()

AI returns an error when the API request fails, the request cannot be understood, or the model response is not valid SPSQ. No output file is created by this API; callers can inspect RawContent or render the returned LoadedContext as usual. AI accepts a context.Context for cancellation and automatically asks the model to repair invalid SPSQ responses up to two times. English prompts that use supported mental-state or profile terms also receive semantic validation of beat ranges, carriers, and timeline progression.

Sequence Inspection

Use Duration to retrieve the total duration of the loaded sequence as a time.Duration:

duration := loaded.Duration()

Render Status

The Go API is silent by default. WithProgress(writer, colors) enables a responsive terminal progress bar, or plain start and completion summaries for non-terminal writers. WithVerbose(writer, colors) enables detailed period and track reports instead. The last call selects the mode; a nil writer disables output. Progress measures generated audio, not subsequent external encoder finalization.

Thread Safety

AppContext methods are safe for concurrent use because configuration methods return new instances rather than mutating the original context.

More Information

For complete documentation and examples, see: https://github.com/synapseq-foundation/synapseq

Types

type AIOptions struct {
	Model       string
	BaseURL     string
	Provider    AIProvider
	Temperature float64
	Timeout     time.Duration
}

AIOptions configures a model used to generate SPSQ text. Empty Model and BaseURL values use SYNAPSEQ_AI_MODEL and SYNAPSEQ_AI_BASE_URL, then SynapSeq defaults. Provider accepts AIProviderDefault, AIProviderAppleFoundation, or an empty value. Apple Foundation is available only in darwin/arm64 builds, uses the local fm command, and ignores BaseURL and Temperature. Temperature must be between 0 and 2. Timeout must be greater than zero.

type AIProvider string

AIProvider selects the compatibility behavior for an AI service.

const (
	// AIProviderDefault uses the standard OpenAI-compatible request behavior.
	AIProviderDefault AIProvider = "default"
	// AIProviderAppleFoundation uses Apple's local Foundation Models through fmgo.
	AIProviderAppleFoundation AIProvider = "apple-foundation"
)
type AppContext struct {
	// contains filtered or unexported fields
}

AppContext holds the configuration for the application. It provides a safe, immutable context for sequence processing. Methods that modify the context return a new instance.

func NewAppContext() *AppContext

NewAppContext creates a new AppContext instance.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("AppContext created successfully\n")

Output:

AppContext created successfully
func (ac *AppContext) AI(ctx context.Context, prompt string, options *AIOptions) (*LoadedContext, error)

AI generates and validates an SPSQ sequence from prompt using an OpenAI-compatible chat completion API. The API key is read from SYNAPSEQ_AI_API_KEY. The request stops when ctx is canceled or its configured timeout expires.

Example


if os.Getenv("SYNAPSEQ_AI_API_KEY") == "" {
	return
}

ctx := synapseq.NewAppContext()
loaded, err := ctx.AI(context.Background(), "Generate a 10 minute relaxation sequence", &synapseq.AIOptions{
	Model:       "local-model",
	BaseURL:     "http://localhost:1234",
	Temperature: 1,
	Timeout:     time.Minute,
})
if err != nil {
	log.Fatal(err)
}

fmt.Print(string(loaded.RawContent()))
func (ac *AppContext) LoadContent(content string) (*LoadedContext, error)

LoadContent loads the sequence from raw text content.

Example


	ctx := synapseq.NewAppContext()

	content := `
alpha
  tone 100 binaural 1 amplitude 1
00:00:00 alpha
00:01:00 alpha
`

	loaded, err := ctx.LoadContent(content)
	if err != nil {
		panic(err)
	}
	_ = loaded

	fmt.Printf("Sequence content loaded successfully\n")

Output:

Sequence content loaded successfully
func (ac *AppContext) LoadFile(path string) (*LoadedContext, error)

LoadFile loads the sequence from the input file.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Sequence loaded successfully\n")

Output:

Sequence loaded successfully
func (ac *AppContext) Verbose() bool

Verbose returns whether verbose mode is enabled. When true, status output will be written to the configured writer.

func (ac *AppContext) WithProgress(data io.Writer, colors bool) *AppContext

WithProgress returns a new AppContext with render progress written to data. Terminal writers display an adaptive bar; other writers receive a plain summary. The last WithProgress or WithVerbose call selects the status mode. A nil writer disables status output. NewAppContext remains silent by default.

func (ac *AppContext) WithVerbose(data io.Writer, colors bool) *AppContext

WithVerbose returns a new AppContext with verbose mode enabled. Status output will be written to the provided writer (typically os.Stderr), and colors controls whether ANSI color sequences are emitted.

Example:

ctx = ctx.WithVerbose(os.Stderr, true)
type Effect struct {
	Type      string
	Value     float64
	Intensity float64
}

Effect holds an effect, including its type, value, and intensity.

type LoadedContext struct {
	// contains filtered or unexported fields
}

LoadedContext holds a loaded sequence and execution settings.

func (lc *LoadedContext) Ambiance() map[string]string

Ambiance returns a defensive copy of ambiance map.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Ambiance retrieved successfully\n")

Output:

Ambiance retrieved successfully
func (lc *LoadedContext) Comments() []string

Comments returns a defensive copy of sequence comments.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Comments retrieved successfully\n")

Output:

Comments retrieved successfully
func (lc *LoadedContext) Duration() time.Duration

Duration returns the duration of the sequence in seconds.

Example

	ctx := synapseq.NewAppContext()

	loaded, err := ctx.LoadContent(`alpha
  waveform sine tone 300 binaural 10 amplitude 20

00:00:00 alpha
00:01:00 alpha
`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Duration: %s\n", loaded.Duration())

Output:

Duration: 1m0s
func (lc *LoadedContext) Extends() []string

Extends returns a defensive copy of extends list.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Extends list retrieved successfully\n")

Output:

Extends list retrieved successfully
func (lc *LoadedContext) JSON() ([]byte, error)

JSON returns an indented JSON representation of the loaded sequence.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("JSON dump bytes generated successfully\n")

Output:

JSON dump bytes generated successfully
func (lc *LoadedContext) Music() map[string]string

Music returns a defensive copy of music map.

func (lc *LoadedContext) Presets() []Preset

Presets returns a defensive copy of sequence presets.

Example

	ctx := synapseq.NewAppContext()

	loaded, err := ctx.LoadContent(`alpha
  waveform sine tone 300 binaural 10 amplitude 20
  noise pink smooth 5 amplitude 10

00:00:00 alpha
00:01:00 alpha
`)
	if err != nil {
		log.Fatal(err)
	}

	presets := loaded.Presets()

	fmt.Printf("Presets: %d\n", len(presets))
	fmt.Printf("Preset: %s\n", presets[0].Name)
	fmt.Printf("Tracks: %d\n", len(presets[0].Tracks))
	fmt.Printf("Track 1: %s %.2f %.2f %.2f %.2f\n",
		presets[0].Tracks[0].Type,
		presets[0].Tracks[0].Carrier,
		presets[0].Tracks[0].Resonance,
		presets[0].Tracks[0].Amplitude[0],
		presets[0].Tracks[0].Amplitude[1],
	)

Output:

Presets: 1
Preset: alpha
Tracks: 2
Track 1: binaural 300.00 10.00 20.00 20.00
func (lc *LoadedContext) RawContent() []byte

RawContent returns a defensive copy of raw content.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Raw content retrieved successfully\n")

Output:

Raw content retrieved successfully
func (lc *LoadedContext) SampleRate() int

SampleRate returns the sample rate from the loaded sequence options.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Sample rate retrieved successfully\n")

Output:

Sample rate retrieved successfully
func (lc *LoadedContext) Stream(data io.Writer) error

Stream generates the raw audio stream from the loaded sequence.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("RAW data streamed successfully\n")

Output:

RAW data streamed successfully
func (lc *LoadedContext) Timeline() []TimelineEntry

Timeline returns a defensive summary copy of sequence timeline entries.

Example

	ctx := synapseq.NewAppContext()

	loaded, err := ctx.LoadContent(`alpha
  waveform sine tone 300 binaural 10 amplitude 20

beta
  waveform sine tone 200 monaural 8 amplitude 15

00:00:00 alpha steady 0
00:01:00 beta smooth 2
`)
	if err != nil {
		log.Fatal(err)
	}

	timeline := loaded.Timeline()

	fmt.Printf("Timeline: %d\n", len(timeline))
	fmt.Printf("Entry 1: %s %s %s %d\n",
		timeline[0].Timestamp,
		timeline[0].PresetName,
		timeline[0].Transition,
		timeline[0].Steps,
	)
	fmt.Printf("Entry 2: %s %s %s %d\n",
		timeline[1].Timestamp,
		timeline[1].PresetName,
		timeline[1].Transition,
		timeline[1].Steps,
	)

Output:

Timeline: 2
Entry 1: 00:00:00 alpha steady 0
Entry 2: 00:01:00 beta smooth 2
func (lc *LoadedContext) Volume() int

Volume returns the volume from the loaded sequence options.

Example


ctx := synapseq.NewAppContext()
_ = ctx

fmt.Printf("Volume retrieved successfully\n")

Output:

Volume retrieved successfully
func (lc *LoadedContext) WAV(outputFile string) error

WAV generates the WAV file from the loaded sequence.

Example


ctx := synapseq.NewAppContext()

ctx = ctx.WithVerbose(os.Stderr, true)

fmt.Printf("WAV file generated successfully\n")

Output:

WAV file generated successfully
type Preset struct {
	Name   string
	Tracks []Track
}

Preset holds a preset, including its name and tracks.

type TimelineEntry struct {
	Timestamp  string
	PresetName string
	Transition string
	Steps      int
	Line       string
}

TimelineEntry holds a timeline entry for a preset, including its time, preset name, transition, steps, and line.

type Track struct {
	Index       int
	Waveform    string
	Type        string
	Carrier     float64
	Resonance   float64
	Amplitude   [2]float64
	SourceName  string
	NoiseSmooth float64
	Effect      Effect
	Line        string
}

Track holds a track, including its index, type, line, amplitude, carrier, resonance, waveform, source name, noise smooth, and effect.

All Go packages