Documentation
¶
Overview ¶
Package audioconv decodes, processes, and encodes game audio assets in pure Go, with optional AAC and MP3 conversion via ffmpeg or macOS afconvert when present on PATH.
Index ¶
- Variables
- func ConvertBuffer(ctx context.Context, buf *Buffer, outPath string, format Format, opts Options) error
- func ConvertFile(ctx context.Context, inPath, outPath string, format Format, opts Options) error
- func ConvertToAAC(ctx context.Context, wavPath, outPath string, bitrateKbps int) error
- func ConvertToMP3(ctx context.Context, wavPath, outPath string, bitrateKbps int) error
- func EncodeWAV(w io.Writer, buf *Buffer) error
- func WriteWAVFile(path string, buf *Buffer) error
- type Buffer
- func (b *Buffer) Clone() *Buffer
- func (b *Buffer) ConvertChannels(targetChannels int) (*Buffer, error)
- func (b *Buffer) Duration() time.Duration
- func (b *Buffer) Frames() int
- func (b *Buffer) NormalizePeak(targetDBFS float64) *Buffer
- func (b *Buffer) NormalizeRMS(targetDBFS float64) *Buffer
- func (b *Buffer) Peak() float64
- func (b *Buffer) PeakDBFS() float64
- func (b *Buffer) RMS() float64
- func (b *Buffer) RMSDBFS() float64
- func (b *Buffer) Resample(targetRate int) (*Buffer, error)
- func (b *Buffer) Validate() error
- type CommandRunner
- type Encoder
- func (e *Encoder) ConvertBuffer(ctx context.Context, buf *Buffer, outPath string, format Format, opts Options) error
- func (e *Encoder) ConvertFile(ctx context.Context, inPath, outPath string, format Format, opts Options) error
- func (e *Encoder) ConvertToAAC(ctx context.Context, wavPath, outPath string, bitrateKbps int) error
- func (e *Encoder) ConvertToMP3(ctx context.Context, wavPath, outPath string, bitrateKbps int) error
- func (e *Encoder) Tool(ctx context.Context, format Format) (string, error)
- type Format
- type Loop
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrEncoderNotFound = errors.New("audioconv: external audio encoder not found on PATH")
ErrEncoderNotFound is returned when no external encoder (ffmpeg, or afconvert on macOS for AAC) is found on PATH.
Functions ¶
func ConvertBuffer ¶
func ConvertBuffer(ctx context.Context, buf *Buffer, outPath string, format Format, opts Options) error
ConvertBuffer processes buf with opts and writes it to outPath in format.
func ConvertFile ¶
ConvertFile reads the WAV file at inPath, applies opts, and writes it to outPath in format.
func ConvertToAAC ¶
ConvertToAAC converts the WAV file at wavPath to AAC at outPath using ffmpeg or macOS afconvert.
func ConvertToMP3 ¶
ConvertToMP3 converts the WAV file at wavPath to MP3 at outPath using ffmpeg.
func EncodeWAV ¶
EncodeWAV writes buf as a standard 16-bit signed little-endian PCM RIFF/WAVE stream, followed by a smpl chunk holding buf.Loop as a forward loop that repeats forever when it is set.
Example ¶
EncodeWAV writes a Buffer as a WAV file and DecodeWAV reads one back.
package main
import (
"bytes"
"fmt"
"github.com/nsgo-dev/game/pkg/tooling/audioconv"
)
func main() {
buf := &audioconv.Buffer{SampleRate: 8000, Channels: 1, Samples: []float64{0, 0.5, -0.5, 0}}
var wav bytes.Buffer
if err := audioconv.EncodeWAV(&wav, buf); err != nil {
fmt.Println(err)
return
}
back, err := audioconv.DecodeWAV(&wav)
fmt.Println(err, back.SampleRate, back.Channels, back.Frames())
}
Output: <nil> 8000 1 4
func WriteWAVFile ¶
WriteWAVFile encodes buf as a 16-bit PCM WAV file at path.
Types ¶
type Buffer ¶
type Buffer struct {
// SampleRate is the number of frames per second, such as 44100 or 22050.
SampleRate int
// Channels is 1 for mono or 2 for stereo.
Channels int
// Samples stores interleaved channel samples of length Frames() * Channels.
Samples []float64
// Loop is the region a player repeats, or nil for none. EncodeWAV writes it in a smpl chunk and DecodeWAV reads the first forward loop of one; Resample scales it to the new rate, and ConvertChannels, Process and Clone keep it.
Loop *Loop
}
Buffer holds interleaved floating-point PCM audio samples normalized to [-1, 1].
func ConvertChannels ¶
ConvertChannels converts buf between mono (1) and stereo (2), returning a new Buffer.
func DecodeWAV ¶
DecodeWAV reads a RIFF/WAVE stream containing 8-bit unsigned, 16-bit signed, 24-bit signed, 32-bit signed, or 32-bit/64-bit IEEE float PCM audio (mono or stereo). The first forward loop of a smpl chunk becomes the Buffer's Loop when it lies inside the audio.
func Process ¶
Process applies channel conversion, resampling, and loudness normalization to a copy of buf according to opts.
Example ¶
Process prepares a recording for the game: it resamples, downmixes and normalizes the peak level, all in Go without external tools.
package main
import (
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/tooling/audioconv"
)
func main() {
src := &audioconv.Buffer{SampleRate: 44100, Channels: 2, Samples: make([]float64, 2*44100)}
for i := range 44100 {
v := 0.25 * math.Sin(2*math.Pi*440*float64(i)/44100)
src.Samples[2*i], src.Samples[2*i+1] = v, v
}
peak := -1.0
out, err := audioconv.Process(src, audioconv.Options{SampleRate: 22050, Channels: 1, PeakDBFS: &peak})
if err != nil {
fmt.Println(err)
return
}
maxAbs := 0.0
for _, s := range out.Samples {
maxAbs = max(maxAbs, math.Abs(s))
}
fmt.Printf("%d Hz, %d channel, %d frames, peak %.1f dBFS\n", out.SampleRate, out.Channels, out.Frames(), 20*math.Log10(maxAbs))
}
Output: 22050 Hz, 1 channel, 22050 frames, peak -1.0 dBFS
func ReadWAVFile ¶
ReadWAVFile reads and decodes a WAV file from disk.
func Resample ¶
Resample returns a new Buffer resampled from buf.SampleRate to targetRate Hz using Hann-windowed sinc interpolation with anti-aliasing when downsampling. Its Loop is buf's scaled to the new rate, each end rounded to the nearest frame.
func (*Buffer) ConvertChannels ¶
ConvertChannels returns a copy of b converted to targetChannels (1 for mono, 2 for stereo).
func (*Buffer) NormalizePeak ¶
NormalizePeak scales b's samples in place so the peak amplitude reaches targetDBFS, returning b for chaining. Silent buffers are left unchanged. If targetDBFS is above 0 dBFS, peaks are protected by a soft-knee limiter.
func (*Buffer) NormalizeRMS ¶
NormalizeRMS scales b's samples in place so the RMS loudness targets targetDBFS, returning b for chaining. Silent buffers are left unchanged. When scaling would push any sample past ±1.0, a smooth C1 soft-knee limiter keeps all samples strictly within (-1, 1) without hard clipping.
func (*Buffer) RMSDBFS ¶
RMSDBFS returns the root-mean-square amplitude in dBFS, or -Inf for silence.
type CommandRunner ¶
type CommandRunner interface {
LookPath(file string) (string, error)
Run(ctx context.Context, name string, args ...string) ([]byte, error)
}
CommandRunner locates and executes external encoder commands. Provide a custom implementation on Encoder to test encoding without spawning real subprocesses.
type Encoder ¶
type Encoder struct {
// Runner invokes external encoder binaries; uses os/exec when nil.
Runner CommandRunner
// GOOS overrides runtime.GOOS when deciding whether macOS afconvert may be used.
GOOS string
}
Encoder converts PCM audio to WAV, AAC, or MP3. WAV encoding runs in pure Go; AAC and MP3 delegate to ffmpeg (or macOS afconvert for AAC) via Runner.
func (*Encoder) ConvertBuffer ¶
func (e *Encoder) ConvertBuffer(ctx context.Context, buf *Buffer, outPath string, format Format, opts Options) error
ConvertBuffer processes buf according to opts and writes it to outPath in format. A WAV file keeps buf.Loop, scaled to the output rate, in its smpl chunk; AAC and MP3 files carry no loop points.
func (*Encoder) ConvertFile ¶
func (e *Encoder) ConvertFile(ctx context.Context, inPath, outPath string, format Format, opts Options) error
ConvertFile reads the WAV file at inPath, applies opts, and writes it to outPath in format.
func (*Encoder) ConvertToAAC ¶
ConvertToAAC converts the WAV file at wavPath to AAC at outPath using ffmpeg, falling back to afconvert on macOS.
func (*Encoder) ConvertToMP3 ¶
ConvertToMP3 converts the WAV file at wavPath to MP3 at outPath using ffmpeg.
func (*Encoder) Tool ¶
Tool describes the encoder ConvertBuffer uses for format on this machine, so a caller that caches converted files can tell when the same input would now convert to different bytes. It is "" for WAV, which is encoded in Go. For AAC and MP3 it names the external encoder and, for ffmpeg, the first line of its -version output, such as "ffmpeg version 7.1.1"; afconvert reports no version, so it is only "afconvert". It returns an error wrapping ErrEncoderNotFound when no encoder is available.
type Format ¶
type Format string
Format names an output audio format.
func ParseFormat ¶
ParseFormat parses a case-insensitive format name ("wav", "aac", or "mp3").
type Loop ¶
type Loop struct {
// Start is the first frame of the loop.
Start int
// End is the frame after the loop's last one; it must be above Start and at most the buffer's Frames.
End int
}
Loop is a region of a Buffer that a player repeats, in sample frames: from Start up to, but not including, End.
type Options ¶
type Options struct {
// SampleRate resamples audio to this rate in Hz when > 0.
SampleRate int
// Channels converts audio to 1 (mono) or 2 (stereo) when > 0.
Channels int
// PeakDBFS normalizes peak sample amplitude to this level in dBFS when non-nil (for example -1.0).
PeakDBFS *float64
// RMSDBFS normalizes RMS loudness to this level in dBFS when non-nil (for example -14.0), applying a soft-knee limiter when peaks would exceed 0 dBFS.
RMSDBFS *float64
// Bitrate sets the target bitrate in kbps for lossy output formats (AAC and MP3), defaulting to 128 when <= 0.
Bitrate int
}
Options configures audio processing before encoding.