audioconv

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func 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 ConvertToAAC

func ConvertToAAC(ctx context.Context, wavPath, outPath string, bitrateKbps int) error

ConvertToAAC converts the WAV file at wavPath to AAC at outPath using ffmpeg or macOS afconvert.

func ConvertToMP3

func ConvertToMP3(ctx context.Context, wavPath, outPath string, bitrateKbps int) error

ConvertToMP3 converts the WAV file at wavPath to MP3 at outPath using ffmpeg.

func EncodeWAV

func EncodeWAV(w io.Writer, buf *Buffer) error

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

func WriteWAVFile(path string, buf *Buffer) error

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

func ConvertChannels(buf *Buffer, targetChannels int) (*Buffer, error)

ConvertChannels converts buf between mono (1) and stereo (2), returning a new Buffer.

func DecodeWAV

func DecodeWAV(r io.Reader) (*Buffer, error)

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

func Process(buf *Buffer, opts Options) (*Buffer, error)

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

func ReadWAVFile(path string) (*Buffer, error)

ReadWAVFile reads and decodes a WAV file from disk.

func Resample

func Resample(buf *Buffer, targetRate int) (*Buffer, error)

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) Clone

func (b *Buffer) Clone() *Buffer

Clone returns a deep copy of b.

func (*Buffer) ConvertChannels

func (b *Buffer) ConvertChannels(targetChannels int) (*Buffer, error)

ConvertChannels returns a copy of b converted to targetChannels (1 for mono, 2 for stereo).

func (*Buffer) Duration

func (b *Buffer) Duration() time.Duration

Duration returns the playback duration of b.

func (*Buffer) Frames

func (b *Buffer) Frames() int

Frames returns the number of multi-channel sample frames in b.

func (*Buffer) NormalizePeak

func (b *Buffer) NormalizePeak(targetDBFS float64) *Buffer

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

func (b *Buffer) NormalizeRMS(targetDBFS float64) *Buffer

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) Peak

func (b *Buffer) Peak() float64

Peak returns the maximum absolute sample amplitude in b.

func (*Buffer) PeakDBFS

func (b *Buffer) PeakDBFS() float64

PeakDBFS returns the peak amplitude in dBFS, or -Inf for silence.

func (*Buffer) RMS

func (b *Buffer) RMS() float64

RMS returns the root-mean-square amplitude across all samples in b.

func (*Buffer) RMSDBFS

func (b *Buffer) RMSDBFS() float64

RMSDBFS returns the root-mean-square amplitude in dBFS, or -Inf for silence.

func (*Buffer) Resample

func (b *Buffer) Resample(targetRate int) (*Buffer, error)

Resample returns a copy of b resampled to targetRate Hz using Hann-windowed sinc interpolation.

func (*Buffer) Validate

func (b *Buffer) Validate() error

Validate checks that b describes a supported mono or stereo PCM buffer.

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

func (e *Encoder) ConvertToAAC(ctx context.Context, wavPath, outPath string, bitrateKbps int) error

ConvertToAAC converts the WAV file at wavPath to AAC at outPath using ffmpeg, falling back to afconvert on macOS.

func (*Encoder) ConvertToMP3

func (e *Encoder) ConvertToMP3(ctx context.Context, wavPath, outPath string, bitrateKbps int) error

ConvertToMP3 converts the WAV file at wavPath to MP3 at outPath using ffmpeg.

func (*Encoder) Tool

func (e *Encoder) Tool(ctx context.Context, format Format) (string, error)

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.

const (
	FormatWAV Format = "wav"
	FormatAAC Format = "aac"
	FormatMP3 Format = "mp3"
)

func ParseFormat

func ParseFormat(s string) (Format, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL