sfx-maker: sfxc - sfxr-style .sfx text presets -> 16-bit WAV synthesis
- waves: square (duty), saw, sine, triangle, pitched noise (seeded, deterministic) - envelope attack/sustain/decay, freq slide, vibrato, arpeggio jump, one-pole low/high-pass filters, clamped output - presets blip/coin/explosion/hurt/jump/laser/powerup with seeded variants; preset writes editable .sfx or renders .wav directly - go tests: parse/validate, determinism, per-preset RMS, WAV header roundtrip Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MmdG9GqfSWCzts7AkDwRDh
This commit is contained in:
223
sfx-maker/sfx/params.go
Normal file
223
sfx-maker/sfx/params.go
Normal file
@@ -0,0 +1,223 @@
|
||||
// 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()
|
||||
}
|
||||
114
sfx-maker/sfx/presets.go
Normal file
114
sfx-maker/sfx/presets.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package sfx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Preset returns ready-made parameters for classic game sounds.
|
||||
// seed 0 gives the canonical version; other seeds vary it slightly so
|
||||
// agents can generate alternatives ("give me three coin variants").
|
||||
func Preset(name string, seed int64) (*Params, error) {
|
||||
p := Defaults()
|
||||
p.Name = name
|
||||
switch name {
|
||||
case "jump":
|
||||
p.Wave = "square"
|
||||
p.Duty = 0.5
|
||||
p.Freq = 330
|
||||
p.FreqSlide = 900
|
||||
p.Attack = 0.01
|
||||
p.Sustain = 0.08
|
||||
p.Decay = 0.18
|
||||
case "coin":
|
||||
p.Wave = "square"
|
||||
p.Duty = 0.5
|
||||
p.Freq = 988
|
||||
p.ArpFactor = 1.335 // up a fourth: B5 -> E6
|
||||
p.ArpTime = 0.06
|
||||
p.Attack = 0.005
|
||||
p.Sustain = 0.08
|
||||
p.Decay = 0.25
|
||||
case "laser":
|
||||
p.Wave = "saw"
|
||||
p.Freq = 1400
|
||||
p.FreqSlide = -6000
|
||||
p.Attack = 0.005
|
||||
p.Sustain = 0.05
|
||||
p.Decay = 0.12
|
||||
p.HighPass = 300
|
||||
case "explosion":
|
||||
p.Wave = "noise"
|
||||
p.Freq = 900
|
||||
p.FreqSlide = -600
|
||||
p.Attack = 0.01
|
||||
p.Sustain = 0.15
|
||||
p.Decay = 0.55
|
||||
p.LowPass = 2200
|
||||
case "hurt":
|
||||
p.Wave = "saw"
|
||||
p.Freq = 300
|
||||
p.FreqSlide = -700
|
||||
p.Attack = 0.005
|
||||
p.Sustain = 0.04
|
||||
p.Decay = 0.14
|
||||
case "powerup":
|
||||
p.Wave = "square"
|
||||
p.Duty = 0.4
|
||||
p.Freq = 220
|
||||
p.FreqSlide = 700
|
||||
p.VibratoDepth = 25
|
||||
p.VibratoRate = 9
|
||||
p.Attack = 0.01
|
||||
p.Sustain = 0.25
|
||||
p.Decay = 0.25
|
||||
case "blip":
|
||||
p.Wave = "square"
|
||||
p.Duty = 0.4
|
||||
p.Freq = 660
|
||||
p.Attack = 0.002
|
||||
p.Sustain = 0.03
|
||||
p.Decay = 0.05
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown preset %q (available: %s)", name, PresetNames())
|
||||
}
|
||||
if seed != 0 {
|
||||
vary(&p, seed)
|
||||
}
|
||||
if err := p.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("preset %s (seed %d): %w", name, seed, err)
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// vary nudges the tonal parameters deterministically from the seed.
|
||||
func vary(p *Params, seed int64) {
|
||||
rng := rand.New(rand.NewSource(seed))
|
||||
jitter := func(v, amount float64) float64 {
|
||||
return v * (1 + amount*(rng.Float64()*2-1))
|
||||
}
|
||||
p.Freq = jitter(p.Freq, 0.15)
|
||||
p.FreqSlide = jitter(p.FreqSlide, 0.25)
|
||||
p.Sustain = jitter(p.Sustain, 0.2)
|
||||
p.Decay = jitter(p.Decay, 0.2)
|
||||
if p.ArpFactor != 0 {
|
||||
p.ArpFactor = jitter(p.ArpFactor, 0.05)
|
||||
}
|
||||
p.Seed = seed // noise variation too
|
||||
}
|
||||
|
||||
var presetNames = []string{"blip", "coin", "explosion", "hurt", "jump", "laser", "powerup"}
|
||||
|
||||
// PresetNames lists the available presets, sorted.
|
||||
func PresetNames() string {
|
||||
sort.Strings(presetNames)
|
||||
out := ""
|
||||
for i, n := range presetNames {
|
||||
if i > 0 {
|
||||
out += ", "
|
||||
}
|
||||
out += n
|
||||
}
|
||||
return out
|
||||
}
|
||||
164
sfx-maker/sfx/sfx_test.go
Normal file
164
sfx-maker/sfx/sfx_test.go
Normal file
@@ -0,0 +1,164 @@
|
||||
package sfx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseAndValidate(t *testing.T) {
|
||||
src := `
|
||||
# a jump
|
||||
sfx: jump
|
||||
wave: square
|
||||
freq: 330
|
||||
freq-slide: 900
|
||||
attack: 0.01
|
||||
sustain: 0.08
|
||||
decay: 0.18
|
||||
duty: 0.4
|
||||
`
|
||||
p, err := Parse(strings.NewReader(src))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Name != "jump" || p.Wave != "square" || p.Freq != 330 || p.Duty != 0.4 {
|
||||
t.Errorf("parsed wrong: %+v", p)
|
||||
}
|
||||
if math.Abs(p.Duration()-0.27) > 1e-9 {
|
||||
t.Errorf("duration = %g, want 0.27", p.Duration())
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseErrors(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"unknown key": "wat: 3\n",
|
||||
"bad wave": "wave: wobble\n",
|
||||
"bad value": "freq: abc\n",
|
||||
"zero length": "attack: 0\nsustain: 0\ndecay: 0\n",
|
||||
"volume range": "volume: 2\n",
|
||||
"duty range": "duty: 0.99\n",
|
||||
}
|
||||
for name, src := range cases {
|
||||
if _, err := Parse(strings.NewReader(src)); err == nil {
|
||||
t.Errorf("%s: expected error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderBasics(t *testing.T) {
|
||||
p := Defaults()
|
||||
p.Wave = "sine"
|
||||
p.Attack, p.Sustain, p.Decay = 0.01, 0.05, 0.05
|
||||
samples := Render(&p)
|
||||
want := int(0.11 * 44100)
|
||||
if len(samples) != want {
|
||||
t.Errorf("samples = %d, want %d", len(samples), want)
|
||||
}
|
||||
var peak float64
|
||||
for _, s := range samples {
|
||||
if math.Abs(s) > peak {
|
||||
peak = math.Abs(s)
|
||||
}
|
||||
if s > 1 || s < -1 {
|
||||
t.Fatalf("sample %g out of range", s)
|
||||
}
|
||||
}
|
||||
if peak < 0.5 {
|
||||
t.Errorf("peak %g suspiciously quiet", peak)
|
||||
}
|
||||
// end of decay should be silent-ish
|
||||
tail := samples[len(samples)-10:]
|
||||
for _, s := range tail {
|
||||
if math.Abs(s) > 0.1 {
|
||||
t.Errorf("tail sample %g not decayed", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderDeterministic(t *testing.T) {
|
||||
p := Defaults()
|
||||
p.Wave = "noise"
|
||||
p.Seed = 42
|
||||
a := Render(&p)
|
||||
b := Render(&p)
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
t.Fatalf("noise render not deterministic at sample %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllWavesAndPresets(t *testing.T) {
|
||||
for _, w := range []string{"square", "saw", "sine", "triangle", "noise"} {
|
||||
p := Defaults()
|
||||
p.Wave = w
|
||||
if s := Render(&p); len(s) == 0 {
|
||||
t.Errorf("wave %s rendered nothing", w)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"blip", "coin", "explosion", "hurt", "jump", "laser", "powerup"} {
|
||||
p, err := Preset(name, 0)
|
||||
if err != nil {
|
||||
t.Errorf("preset %s: %v", name, err)
|
||||
continue
|
||||
}
|
||||
s := Render(p)
|
||||
var sum float64
|
||||
for _, v := range s {
|
||||
sum += v * v
|
||||
}
|
||||
rms := math.Sqrt(sum / float64(len(s)))
|
||||
if rms < 0.01 {
|
||||
t.Errorf("preset %s is nearly silent (rms %g)", name, rms)
|
||||
}
|
||||
// variants stay valid
|
||||
if _, err := Preset(name, 7); err != nil {
|
||||
t.Errorf("preset %s seed 7: %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := Preset("nope", 0); err == nil {
|
||||
t.Error("unknown preset should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWAVRoundTrip(t *testing.T) {
|
||||
p := Defaults()
|
||||
samples := Render(&p)
|
||||
var buf bytes.Buffer
|
||||
if err := WriteWAV(&buf, samples, p.SampleRate); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sr, bits, ch, dataBytes, err := ReadWAVHeader(&buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sr != 44100 || bits != 16 || ch != 1 {
|
||||
t.Errorf("header: sr=%d bits=%d ch=%d", sr, bits, ch)
|
||||
}
|
||||
if dataBytes != len(samples)*2 {
|
||||
t.Errorf("dataBytes = %d, want %d", dataBytes, len(samples)*2)
|
||||
}
|
||||
if buf.Len() != dataBytes {
|
||||
t.Errorf("body length %d != declared %d", buf.Len(), dataBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParamsWriteRoundTrip(t *testing.T) {
|
||||
p, err := Preset("coin", 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := p.Write(&buf, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
back, err := Parse(&buf)
|
||||
if err != nil {
|
||||
t.Fatalf("re-parse of written .sfx failed: %v\n%s", err, buf.String())
|
||||
}
|
||||
if back.Freq != p.Freq || back.ArpFactor != p.ArpFactor || back.Seed != p.Seed {
|
||||
t.Errorf("roundtrip mismatch: %+v vs %+v", back, p)
|
||||
}
|
||||
}
|
||||
122
sfx-maker/sfx/synth.go
Normal file
122
sfx-maker/sfx/synth.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package sfx
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
// Render synthesizes the effect into float64 samples in [-1, 1].
|
||||
func Render(p *Params) []float64 {
|
||||
sr := float64(p.SampleRate)
|
||||
n := int(p.Duration() * sr)
|
||||
out := make([]float64, n)
|
||||
rng := rand.New(rand.NewSource(p.Seed))
|
||||
|
||||
phase := 0.0
|
||||
noiseVal := 0.0
|
||||
noiseCounter := 0.0
|
||||
|
||||
// one-pole filter states
|
||||
lpState := 0.0
|
||||
hpState := 0.0
|
||||
hpPrevIn := 0.0
|
||||
dt := 1 / sr
|
||||
lpAlpha := 0.0
|
||||
if p.LowPass > 0 {
|
||||
rc := 1 / (2 * math.Pi * p.LowPass)
|
||||
lpAlpha = dt / (rc + dt)
|
||||
}
|
||||
hpAlpha := 0.0
|
||||
if p.HighPass > 0 {
|
||||
rc := 1 / (2 * math.Pi * p.HighPass)
|
||||
hpAlpha = rc / (rc + dt)
|
||||
}
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
t := float64(i) / sr
|
||||
|
||||
f := p.Freq + p.FreqSlide*t
|
||||
if p.ArpFactor != 0 && p.ArpTime > 0 && t >= p.ArpTime {
|
||||
f *= p.ArpFactor
|
||||
}
|
||||
if p.VibratoDepth > 0 && p.VibratoRate > 0 {
|
||||
f += p.VibratoDepth * math.Sin(2*math.Pi*p.VibratoRate*t)
|
||||
}
|
||||
if f < p.FreqMin {
|
||||
f = p.FreqMin
|
||||
}
|
||||
|
||||
var s float64
|
||||
if p.Wave == "noise" {
|
||||
// pitched noise: new random value f*4 times per second
|
||||
noiseCounter += f * 4 * dt
|
||||
if noiseCounter >= 1 || i == 0 {
|
||||
noiseCounter = math.Mod(noiseCounter, 1)
|
||||
noiseVal = rng.Float64()*2 - 1
|
||||
}
|
||||
s = noiseVal
|
||||
} else {
|
||||
phase += f * dt
|
||||
ph := math.Mod(phase, 1)
|
||||
switch p.Wave {
|
||||
case "square":
|
||||
if ph < p.Duty {
|
||||
s = 1
|
||||
} else {
|
||||
s = -1
|
||||
}
|
||||
case "saw":
|
||||
s = 2*ph - 1
|
||||
case "triangle":
|
||||
if ph < 0.5 {
|
||||
s = 4*ph - 1
|
||||
} else {
|
||||
s = 3 - 4*ph
|
||||
}
|
||||
case "sine":
|
||||
s = math.Sin(2 * math.Pi * ph)
|
||||
}
|
||||
}
|
||||
|
||||
s *= envelope(p, t)
|
||||
|
||||
if lpAlpha > 0 {
|
||||
lpState += lpAlpha * (s - lpState)
|
||||
s = lpState
|
||||
}
|
||||
if hpAlpha > 0 {
|
||||
hpState = hpAlpha * (hpState + s - hpPrevIn)
|
||||
hpPrevIn = s
|
||||
s = hpState
|
||||
}
|
||||
|
||||
s *= p.Volume
|
||||
if s > 1 {
|
||||
s = 1
|
||||
} else if s < -1 {
|
||||
s = -1
|
||||
}
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// envelope is a linear attack / sustain / decay gain in 0..1.
|
||||
func envelope(p *Params, t float64) float64 {
|
||||
switch {
|
||||
case t < p.Attack:
|
||||
return t / p.Attack
|
||||
case t < p.Attack+p.Sustain:
|
||||
return 1
|
||||
default:
|
||||
d := t - p.Attack - p.Sustain
|
||||
if p.Decay <= 0 {
|
||||
return 0
|
||||
}
|
||||
g := 1 - d/p.Decay
|
||||
if g < 0 {
|
||||
g = 0
|
||||
}
|
||||
return g
|
||||
}
|
||||
}
|
||||
54
sfx-maker/sfx/wav.go
Normal file
54
sfx-maker/sfx/wav.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package sfx
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
)
|
||||
|
||||
// WriteWAV encodes samples ([-1,1] floats) as a 16-bit mono PCM WAV.
|
||||
func WriteWAV(w io.Writer, samples []float64, sampleRate int) error {
|
||||
dataLen := len(samples) * 2
|
||||
var hdr [44]byte
|
||||
copy(hdr[0:4], "RIFF")
|
||||
binary.LittleEndian.PutUint32(hdr[4:8], uint32(36+dataLen))
|
||||
copy(hdr[8:12], "WAVE")
|
||||
copy(hdr[12:16], "fmt ")
|
||||
binary.LittleEndian.PutUint32(hdr[16:20], 16) // fmt chunk size
|
||||
binary.LittleEndian.PutUint16(hdr[20:22], 1) // PCM
|
||||
binary.LittleEndian.PutUint16(hdr[22:24], 1) // mono
|
||||
binary.LittleEndian.PutUint32(hdr[24:28], uint32(sampleRate)) // sample rate
|
||||
binary.LittleEndian.PutUint32(hdr[28:32], uint32(sampleRate*2)) // byte rate
|
||||
binary.LittleEndian.PutUint16(hdr[32:34], 2) // block align
|
||||
binary.LittleEndian.PutUint16(hdr[34:36], 16) // bits per sample
|
||||
copy(hdr[36:40], "data")
|
||||
binary.LittleEndian.PutUint32(hdr[40:44], uint32(dataLen))
|
||||
if _, err := w.Write(hdr[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
buf := make([]byte, 2*len(samples))
|
||||
for i, s := range samples {
|
||||
v := int16(math.Round(s * 32767))
|
||||
binary.LittleEndian.PutUint16(buf[i*2:], uint16(v))
|
||||
}
|
||||
_, err := w.Write(buf)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadWAVHeader sanity-parses a WAV header (used in tests and info).
|
||||
func ReadWAVHeader(r io.Reader) (sampleRate, bits, channels, dataBytes int, err error) {
|
||||
var hdr [44]byte
|
||||
if _, err = io.ReadFull(r, hdr[:]); err != nil {
|
||||
return
|
||||
}
|
||||
if string(hdr[0:4]) != "RIFF" || string(hdr[8:12]) != "WAVE" {
|
||||
err = fmt.Errorf("not a WAV file")
|
||||
return
|
||||
}
|
||||
channels = int(binary.LittleEndian.Uint16(hdr[22:24]))
|
||||
sampleRate = int(binary.LittleEndian.Uint32(hdr[24:28]))
|
||||
bits = int(binary.LittleEndian.Uint16(hdr[34:36]))
|
||||
dataBytes = int(binary.LittleEndian.Uint32(hdr[40:44]))
|
||||
return
|
||||
}
|
||||
Reference in New Issue
Block a user