// Package sfx synthesizes retro game sound effects (sfxr-style) from // text parameter files and renders them to 16-bit mono WAV. package sfx import ( "bufio" "fmt" "io" "os" "path/filepath" "strconv" "strings" ) // Params describes one sound effect. Zero values mean "off" for the // optional effects; Defaults() fills the required fields. type Params struct { Name string Wave string // square | saw | sine | triangle | noise Volume float64 // 0..1 master gain // envelope, seconds Attack float64 // 0 -> Volume Sustain float64 // hold at Volume Decay float64 // Volume -> 0 Freq float64 // start frequency, Hz FreqSlide float64 // Hz per second, may be negative FreqMin float64 // clamp; sound stops below this (default 20 Hz) Duty float64 // square wave duty cycle 0.05..0.95 (default 0.5) VibratoDepth float64 // Hz VibratoRate float64 // Hz ArpFactor float64 // frequency multiplier applied at ArpTime (0 = off) ArpTime float64 // seconds LowPass float64 // cutoff Hz (0 = off) HighPass float64 // cutoff Hz (0 = off) SampleRate int // default 44100 Seed int64 // noise seed (default 1) } // Defaults returns a Params with sensible base values. func Defaults() Params { return Params{ Wave: "square", Volume: 0.7, Attack: 0.01, Sustain: 0.1, Decay: 0.15, Freq: 440, FreqMin: 20, Duty: 0.5, SampleRate: 44100, Seed: 1, } } // Duration is the total length of the sound in seconds. func (p *Params) Duration() float64 { return p.Attack + p.Sustain + p.Decay } // Validate checks ranges and returns a helpful error. func (p *Params) Validate() error { switch p.Wave { case "square", "saw", "sine", "triangle", "noise": default: return fmt.Errorf("wave %q must be square, saw, sine, triangle or noise", p.Wave) } if p.Volume < 0 || p.Volume > 1 { return fmt.Errorf("volume %g out of range 0-1", p.Volume) } if p.Attack < 0 || p.Sustain < 0 || p.Decay < 0 { return fmt.Errorf("attack/sustain/decay must be >= 0") } if p.Duration() <= 0 { return fmt.Errorf("total duration is 0 — set attack, sustain and/or decay") } if p.Duration() > 10 { return fmt.Errorf("total duration %.2fs is too long (max 10s)", p.Duration()) } if p.Wave != "noise" && (p.Freq <= 0 || p.Freq > 20000) { return fmt.Errorf("freq %g out of range 1-20000 Hz", p.Freq) } if p.Duty < 0.05 || p.Duty > 0.95 { return fmt.Errorf("duty %g out of range 0.05-0.95", p.Duty) } if p.SampleRate < 8000 || p.SampleRate > 96000 { return fmt.Errorf("sample-rate %d out of range 8000-96000", p.SampleRate) } return nil } // ParseFile reads a .sfx file; the name defaults to the file name. func ParseFile(path string) (*Params, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() p, err := Parse(f) if err != nil { return nil, fmt.Errorf("%s: %w", path, err) } if p.Name == "" { p.Name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) } return p, nil } // Parse reads the .sfx text format: one "key: value" per line, // '#' comments. Unknown keys are errors so typos surface immediately. func Parse(r io.Reader) (*Params, error) { p := Defaults() sc := bufio.NewScanner(r) lineNo := 0 for sc.Scan() { lineNo++ line := strings.TrimSpace(sc.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } i := strings.Index(line, ":") if i < 0 { return nil, fmt.Errorf("line %d: want 'key: value', got %q", lineNo, line) } key := strings.ToLower(strings.TrimSpace(line[:i])) val := strings.TrimSpace(line[i+1:]) if j := strings.Index(val, " #"); j >= 0 { // trailing comment val = strings.TrimSpace(val[:j]) } var err error switch key { case "sfx", "name": p.Name = val case "wave": p.Wave = strings.ToLower(val) case "volume": p.Volume, err = strconv.ParseFloat(val, 64) case "attack": p.Attack, err = strconv.ParseFloat(val, 64) case "sustain": p.Sustain, err = strconv.ParseFloat(val, 64) case "decay": p.Decay, err = strconv.ParseFloat(val, 64) case "freq": p.Freq, err = strconv.ParseFloat(val, 64) case "freq-slide": p.FreqSlide, err = strconv.ParseFloat(val, 64) case "freq-min": p.FreqMin, err = strconv.ParseFloat(val, 64) case "duty": p.Duty, err = strconv.ParseFloat(val, 64) case "vibrato-depth": p.VibratoDepth, err = strconv.ParseFloat(val, 64) case "vibrato-rate": p.VibratoRate, err = strconv.ParseFloat(val, 64) case "arpeggio": p.ArpFactor, err = strconv.ParseFloat(val, 64) case "arpeggio-time": p.ArpTime, err = strconv.ParseFloat(val, 64) case "lowpass": p.LowPass, err = strconv.ParseFloat(val, 64) case "highpass": p.HighPass, err = strconv.ParseFloat(val, 64) case "sample-rate": p.SampleRate, err = strconv.Atoi(val) case "seed": p.Seed, err = strconv.ParseInt(val, 10, 64) default: return nil, fmt.Errorf("line %d: unknown key %q", lineNo, key) } if err != nil { return nil, fmt.Errorf("line %d: %s: bad value %q", lineNo, key, val) } } if err := sc.Err(); err != nil { return nil, err } if err := p.Validate(); err != nil { return nil, err } return &p, nil } // Write renders the params back to the .sfx text format (used by the // preset generator so agents get an editable file). func (p *Params) Write(w io.Writer, comment string) error { bw := bufio.NewWriter(w) if comment != "" { fmt.Fprintf(bw, "# %s\n", comment) } fmt.Fprintf(bw, "sfx: %s\nwave: %s\nvolume: %g\n", p.Name, p.Wave, p.Volume) fmt.Fprintf(bw, "attack: %g\nsustain: %g\ndecay: %g\n", p.Attack, p.Sustain, p.Decay) if p.Wave != "noise" { fmt.Fprintf(bw, "freq: %g\n", p.Freq) } if p.FreqSlide != 0 { fmt.Fprintf(bw, "freq-slide: %g\n", p.FreqSlide) } if p.Wave == "square" && p.Duty != 0.5 { fmt.Fprintf(bw, "duty: %g\n", p.Duty) } if p.VibratoDepth > 0 && p.VibratoRate > 0 { fmt.Fprintf(bw, "vibrato-depth: %g\nvibrato-rate: %g\n", p.VibratoDepth, p.VibratoRate) } if p.ArpFactor != 0 { fmt.Fprintf(bw, "arpeggio: %g\narpeggio-time: %g\n", p.ArpFactor, p.ArpTime) } if p.LowPass > 0 { fmt.Fprintf(bw, "lowpass: %g\n", p.LowPass) } if p.HighPass > 0 { fmt.Fprintf(bw, "highpass: %g\n", p.HighPass) } if p.Seed != 1 { fmt.Fprintf(bw, "seed: %d\n", p.Seed) } return bw.Flush() }