audiocodec

package
v0.6.21 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 10 Imported by: ? modules, 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

Rendered for darwin/amd64

Overview

Package audiocodec encodes and decodes float32 PCM audio using macOS AudioToolbox AudioConverter with native Opus and AAC codecs without cgo.

Supported codecs:

  • Opus (kAudioFormatOpus): low-latency speech and general audio at 8, 12, 16, 24, or 48 kHz (20 ms frames by default).
  • AAC (kAudioFormatMPEG4AAC): MPEG-4 AAC-LC at standard sample rates (1024-sample frames).

Zero values of Encoder and Decoder are not usable; construct them with NewEncoder and NewDecoder. Call Encoder.Close and Decoder.Close to release the underlying AudioConverterRef.

Basic usage:

cfg := audiocodec.Config{
	Codec:      audiocodec.Opus,
	SampleRate: 48000,
	Channels:   1,
	BitRate:    48000,
}
enc, err := audiocodec.NewEncoder(cfg)
if err != nil {
	log.Fatal(err)
}
defer enc.Close()

dec, err := audiocodec.NewDecoder(cfg)
if err != nil {
	log.Fatal(err)
}
defer dec.Close()

packets, err := enc.Encode(pcm)
if err != nil {
	log.Fatal(err)
}
for _, pkt := range packets {
	out, err := dec.Decode(pkt)
	if err != nil {
		log.Fatal(err)
	}
	_ = out
}
Example
package main

import (
	"fmt"
	"log"
	"math"

	"github.com/tmc/apple/x/audiocodec"
)

func main() {
	cfg := audiocodec.Config{
		Codec:      audiocodec.Opus,
		SampleRate: 48000,
		Channels:   1,
		BitRate:    48000,
	}
	enc, err := audiocodec.NewEncoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer enc.Close()

	cfg.MagicCookie = enc.MagicCookie()
	dec, err := audiocodec.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer dec.Close()

	// Synthesize 100 ms of a 440 Hz sine wave.
	pcm := make([]float32, 4800)
	for i := range pcm {
		pcm[i] = 0.5 * float32(math.Sin(2*math.Pi*440*float64(i)/48000))
	}

	packets, err := enc.Encode(pcm)
	if err != nil {
		log.Fatal(err)
	}

	var decoded int
	for _, pkt := range packets {
		out, err := dec.Decode(pkt)
		if err != nil {
			log.Fatal(err)
		}
		decoded += len(out)
	}
	fmt.Printf("codec=%s packets=%d decoded_ok=%v\n", cfg.Codec, len(packets), decoded >= 4000)
}
Output:
codec=Opus packets=5 decoded_ok=true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is returned when an operation is attempted on a closed Encoder or Decoder.
	ErrClosed = errors.New("audiocodec: converter closed")
	// ErrInvalidConfig is returned when Config contains unsupported parameters.
	ErrInvalidConfig = errors.New("audiocodec: invalid config")
)

Functions

This section is empty.

Types

type Codec

type Codec uint32

Codec identifies an audio codec supported by AudioToolbox AudioConverter.

const (
	// Opus selects Apple's native Opus codec (kAudioFormatOpus).
	Opus Codec = Codec(coreaudiotypes.KAudioFormatOpus)
	// AAC selects Apple's native MPEG-4 AAC-LC codec (kAudioFormatMPEG4AAC).
	AAC Codec = Codec(coreaudiotypes.KAudioFormatMPEG4AAC)
)

func (Codec) String

func (c Codec) String() string

String returns the human-readable name of the codec.

type Config

type Config struct {
	// Codec selects Opus or AAC. Defaults to Opus if zero.
	Codec Codec
	// SampleRate is the PCM sample rate in Hz. Defaults to 48000 if zero.
	SampleRate int
	// Channels is the number of interleaved audio channels (1 or 2).
	// Defaults to 1 if zero.
	Channels int
	// BitRate is the target encoding bitrate in bits per second (e.g., 32000–64000).
	// Ignored by Decoder. If zero, a sensible default (48000) is used for encoding.
	BitRate int
	// FrameDuration sets the Opus frame duration (default 20ms).
	// Ignored for AAC, which uses 1024-sample frames.
	FrameDuration time.Duration
	// MagicCookie is an optional codec-specific configuration cookie passed to
	// NewDecoder via kAudioConverterDecompressionMagicCookie.
	MagicCookie []byte
}

Config configures an Encoder or Decoder.

type Decoder

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

Decoder decodes compressed Packet values into interleaved float32 PCM samples using Apple's AudioToolbox AudioConverter.

func NewDecoder

func NewDecoder(cfg Config) (*Decoder, error)

NewDecoder creates an audio decoder for the given configuration.

func (*Decoder) Close

func (d *Decoder) Close() error

Close releases the underlying AudioConverterRef. It is safe to call Close more than once.

func (*Decoder) Decode

func (d *Decoder) Decode(pkt Packet) ([]float32, error)

Decode decodes a single compressed packet into interleaved float32 PCM samples.

func (*Decoder) FrameSize

func (d *Decoder) FrameSize() int

FrameSize returns the nominal number of PCM frames per channel decoded per packet.

func (*Decoder) Reset

func (d *Decoder) Reset() error

Reset clears internal decoder state and resets the underlying AudioConverter.

type Encoder

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

Encoder encodes interleaved float32 PCM samples into compressed Packet values using Apple's AudioToolbox AudioConverter.

func NewEncoder

func NewEncoder(cfg Config) (*Encoder, error)

NewEncoder creates an audio encoder for the given configuration.

func (*Encoder) BitRate

func (e *Encoder) BitRate() int

BitRate returns the configured encoding bitrate in bits per second.

func (*Encoder) Close

func (e *Encoder) Close() error

Close releases the underlying AudioConverterRef. It is safe to call Close more than once.

func (*Encoder) Encode

func (e *Encoder) Encode(pcm []float32) ([]Packet, error)

Encode encodes interleaved float32 PCM samples and returns any complete compressed packets produced. Unconsumed trailing samples are buffered until the next Encode, Flush, or Reset call.

func (*Encoder) Flush

func (e *Encoder) Flush() ([]Packet, error)

Flush signals end-of-stream to the encoder, returning any remaining buffered packets, and resets the converter so it can be reused if desired.

func (*Encoder) FrameSize

func (e *Encoder) FrameSize() int

FrameSize returns the number of PCM frames per channel in each encoded packet.

func (*Encoder) MagicCookie

func (e *Encoder) MagicCookie() []byte

MagicCookie returns a copy of the encoder's compression magic cookie, if any.

func (*Encoder) PrimingFrames

func (e *Encoder) PrimingFrames() int

PrimingFrames returns the encoder's leading priming frame count, if reported.

func (*Encoder) Reset

func (e *Encoder) Reset() error

Reset clears internal encoder buffers and resets the underlying AudioConverter.

type Packet

type Packet struct {
	// Data contains the compressed codec payload bytes.
	Data []byte
	// Frames is the number of PCM frames (per channel) represented by this packet.
	Frames int
	// Duration is the playback duration of this packet.
	Duration time.Duration
}

Packet holds one encoded audio packet and its PCM frame count.

Jump to

Keyboard shortcuts

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