sndfile

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 19 Imported by: 1 module, 9 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.

README

sndfile

Read and write sound files in Go, without cgo.

go get github.com/almerlucke/sndfile

Formats

Format Reading Writing
WAV: PCM 8, 16, 24 and 32 bit, float32 and float64, WAVE_FORMAT_EXTENSIBLE yes float32
AIFF and AIFC: PCM 8 to 32 bit, sowt, fl32, fl64 yes AIFC fl32
FLAC yes no
Ogg Vorbis yes no
MP3 (MPEG 1 and 2) yes no

A-law, µ-law, ADPCM, RF64 and the like are not decoded by the Go code, they need the libsndfile build below. The decoders are written in Go (WAV and AIFF are in this package, the others use go-mp3, mewkiz/flac and oggvorbis), so CGO_ENABLED=0 works.

MP3 files are cut to their sound: the encoder delay and padding from the LAME (or Lavc, Lavf) tag are removed, so a gapless file loops without a click. An MP3 without such a tag is left as it is. Mono MP3 files come out as two identical channels, and MPEG 2.5 (8, 11.025 and 12 kHz) is not supported by the pure Go decoder.

libsndfile (optional)

Build with -tags libsndfile to use libsndfile for everything the Go decoders can't open (needs cgo and the libsndfile development files). Without the tag, such a file gives an unsupported format error that says so.

go build -tags libsndfile ./...

Reading

Load a whole file into memory, one buffer per channel:

sf, err := sndfile.NewSoundFile[float32]("kick.wav")
if err != nil {
	return err
}

fmt.Println(sf.NumChannels(), sf.SampleRate(), sf.NumFrames(), sf.Duration())

left := sf.Buffer(0, 0)
v := sf.Lookup(123.5, 0, 0, false) // interpolated lookup at a position in frames

NewMipMapSoundFile also builds band-limited copies of the file for alias-free playback at other speeds (LookupWithSpeed), and ZeroCrossings finds the zero crossings of a channel.

Or stream it from disk, for files that are too large or too long to load:

r, err := sndfile.Open[float32]("long.flac")
if err != nil {
	return err
}
defer r.Close()

info := r.Info() // Channels, SampleRate, Frames

if err := r.SeekFrame(info.Frames / 2); err != nil { // exact, also for mp3 and ogg
	return err
}

buf := make([]float32, 4096*info.Channels) // interleaved
for {
	n, err := r.ReadFrames(buf)
	if err != nil {
		return err
	}
	if n == 0 { // end of file
		break
	}
	process(buf[:n*int64(info.Channels)])
}

The sample type is float32 or float64.

Writing

wr, err := writer.NewWithOptions("out.wav", writer.WAV, 2, 48000, writer.Options{
	ConvertSampleRate: true,
	InputSampleRate:   44100,
	SrConvQuality:     resample.SincBest,
	Normalize:         true,
})
if err != nil {
	return err
}

if err := wr.Write(samples, true); err != nil { // interleaved, true marks the last block
	return err
}

return wr.Close()

Files are written as 32-bit float. The sizes in the header are refreshed about every 1 MiB, so a file that was not closed (a crash) still plays up to that point. Normalize scales to the absolute peak after sample rate conversion.

Resampling

dsp/resample is a Kaiser-windowed sinc resampler with the quality levels of libsamplerate (SincBest, SincMedium, SincFastest, ZeroOrderHold, Linear). The package documentation compares its accuracy and speed with libsamplerate: it is a few dB (SincBest) to about 15 dB (SincMedium, SincFastest) more accurate, and 1.5 to 2 times faster for the usual fractions such as 44100 to 48000 (about 2 times slower for irrational ratios).

rs, err := resample.New(resample.SincBest, 2)
if err != nil {
	return err
}
rs.SetRatio(48000.0 / 44100.0)
out, err := rs.Process(in, false) // in and out are interleaved; true for the last block

Other packages

  • dsp/filters: windowed-sinc low-pass and high-pass filter coefficients
  • dsp/windows: window functions (Blackman, Hamming, Nuttall, ...)

Testing

go test ./...                       # pure Go
go test -tags libsndfile ./...      # also the libsndfile fallback

testdata/gen.sh regenerates the fixture files (needs ffmpeg), each with a .f32 reference of the expected samples.

License

MIT, see LICENSE.

Documentation

Index

Constants

View Source
const (
	DirectionAny  = 0
	DirectionUp   = 1
	DirectionDown = -1
)

Variables

View Source
var MipMapCache string

MipMapCache is a folder where the mipmaps of the files are kept, so that a file is filtered once and read back after that: building the lower resolutions of a big instrument takes seconds to a minute, reading them takes a moment. "" is no cache. A file is kept by its path, size and time, and the settings of the filters: a file that changes is made again

Functions

func SpeedToMipMapDepth

func SpeedToMipMapDepth(speed float64) int

Types

type Info

type Info struct {
	Channels   int
	SampleRate float64
	// Frames is the length of the file in frames (a frame has a sample of every channel)
	Frames int64
}

Info describes a sound file that is open for reading

type LookupParam

type LookupParam[T float.Float] struct {
	Index1   int64
	Index2   int64
	Fraction float64
}

func NewLookupParam

func NewLookupParam[T float.Float](pos float64, n int64, wrap bool) *LookupParam[T]

func (*LookupParam[T]) Lookup

func (lp *LookupParam[T]) Lookup(b []T) T

type MipMap

type MipMap[T float.Float] struct {
	// contains filtered or unexported fields
}

func NewMipMap

func NewMipMap[T float.Float](buf []T, sampleRate float64, depth int) (*MipMap[T], error)

func (*MipMap[T]) Buffer

func (mm *MipMap[T]) Buffer(depth int) []T

func (*MipMap[T]) Depth

func (mm *MipMap[T]) Depth() int

func (*MipMap[T]) Length

func (mm *MipMap[T]) Length() int

func (*MipMap[T]) Lookup

func (mm *MipMap[T]) Lookup(pos float64, depth int, wrap bool) T

type MipMapSoundFile

type MipMapSoundFile[T float.Float] struct {
	// contains filtered or unexported fields
}

func MustMipMapSoundFile

func MustMipMapSoundFile[T float.Float](filePath string, depth int) *MipMapSoundFile[T]

func NewMipMapSoundFile

func NewMipMapSoundFile[T float.Float](filePath string, depth int) (*MipMapSoundFile[T], error)

func (*MipMapSoundFile[T]) Buffer

func (sf *MipMapSoundFile[T]) Buffer(channel int, depth int) []T

func (*MipMapSoundFile[T]) Depth

func (sf *MipMapSoundFile[T]) Depth() int

func (*MipMapSoundFile[T]) Duration

func (sf *MipMapSoundFile[T]) Duration() float64

func (*MipMapSoundFile[T]) Lookup

func (sf *MipMapSoundFile[T]) Lookup(pos float64, channel int, depth int, wrap bool) T

func (*MipMapSoundFile[T]) LookupAll

func (sf *MipMapSoundFile[T]) LookupAll(pos float64, depth int, wrap bool) []T

func (*MipMapSoundFile[T]) LookupAllWithSpeed

func (sf *MipMapSoundFile[T]) LookupAllWithSpeed(pos float64, speed float64, wrap bool) []T

func (*MipMapSoundFile[T]) LookupWithSpeed

func (sf *MipMapSoundFile[T]) LookupWithSpeed(pos float64, channel int, speed float64, wrap bool) T

func (*MipMapSoundFile[T]) NumChannels

func (sf *MipMapSoundFile[T]) NumChannels() int

func (*MipMapSoundFile[T]) NumFrames

func (sf *MipMapSoundFile[T]) NumFrames() int64

func (*MipMapSoundFile[T]) SampleRate

func (sf *MipMapSoundFile[T]) SampleRate() float64

func (*MipMapSoundFile[T]) ZeroCrossings

func (sf *MipMapSoundFile[T]) ZeroCrossings(channel int) ZeroCrossings

type Reader

type Reader[T float.Float] interface {
	// Info is the number of channels, the sample rate and the length of the file
	Info() Info
	// SeekFrame moves to a frame, counted from the start of the file. frame may be Info().Frames (the end), but not further. Seeking lossy files
	// (mp3, ogg) is exact to the frame
	SeekFrame(frame int64) error
	// ReadFrames fills buf with interleaved samples, as many whole frames as fit in it and the file has left, and gives the number of frames. At the
	// end of the file it gives 0 and no error, like libsndfile does
	ReadFrames(buf []T) (int64, error)
	// Close closes the file
	Close() error
}

Reader streams the frames of a sound file from disk, for files that are too big to load, or that are read from the middle on (an instrument that plays from disk, a loop). A Reader is not safe for use from more than one goroutine.

It is the small part of libsndfile that a streamer needs, so that a streamer does not need libsndfile itself: Open reads wav, aiff, mp3, flac and ogg vorbis in pure Go, and all the other formats with the libsndfile build tag.

func Open

func Open[T float.Float](filePath string) (Reader[T], error)

Open opens a sound file for streaming. The pure-Go readers handle wav, aiff, mp3, flac and ogg vorbis; other formats need the libsndfile build tag

type SoundBank

type SoundBank[T float.Float] map[string]SoundFiler[T]

type SoundFile

type SoundFile[T float.Float] struct {
	// contains filtered or unexported fields
}

SoundFile contains sound file deinterleaved samples and implements SoundFiler interface

func MustSoundFile

func MustSoundFile[T float.Float](filePath string) *SoundFile[T]

MustSoundFile must load a sound file

func NewSoundFile

func NewSoundFile[T float.Float](filePath string) (*SoundFile[T], error)

func (*SoundFile[T]) Buffer

func (sf *SoundFile[T]) Buffer(channel int, _ int) []T

func (*SoundFile[T]) Depth

func (sf *SoundFile[T]) Depth() int

func (*SoundFile[T]) Duration

func (sf *SoundFile[T]) Duration() float64

func (*SoundFile[T]) Lookup

func (sf *SoundFile[T]) Lookup(pos float64, channel int, _ int, wrap bool) T

func (*SoundFile[T]) LookupAll

func (sf *SoundFile[T]) LookupAll(pos float64, _ int, wrap bool) []T

func (*SoundFile[T]) NumChannels

func (sf *SoundFile[T]) NumChannels() int

func (*SoundFile[T]) NumFrames

func (sf *SoundFile[T]) NumFrames() int64

func (*SoundFile[T]) SampleRate

func (sf *SoundFile[T]) SampleRate() float64

func (*SoundFile[T]) ZeroCrossings

func (sf *SoundFile[T]) ZeroCrossings(channel int) ZeroCrossings

type SoundFiler

type SoundFiler[T float.Float] interface {
	NumChannels() int
	SampleRate() float64
	NumFrames() int64
	Duration() float64
	Depth() int
	Buffer(channel int, depth int) []T
	Lookup(pos float64, channel int, depth int, wrap bool) T
	LookupAll(pos float64, depth int, wrap bool) []T
	ZeroCrossings(channel int) ZeroCrossings
}

type ZeroCrossing

type ZeroCrossing struct {
	PositionFrames int64
	Position       float64
	Direction      int
}

type ZeroCrossings

type ZeroCrossings []ZeroCrossing

func (ZeroCrossings) NearestPos

func (z ZeroCrossings) NearestPos(pos float64, direction int) (ZeroCrossing, bool)

NearestPos returns the zero crossing closest to pos (0-1), optionally only crossings in the given direction. Zero crossings are sorted by position, so it uses a binary search: fast also for long files with many crossings (granular sources call it for every grain)

func (ZeroCrossings) NearestPosFrames

func (z ZeroCrossings) NearestPosFrames(pos int64, direction int) (ZeroCrossing, bool)

NearestPosFrames returns the zero crossing closest to the frame position, optionally only crossings in the given direction

Directories

Path Synopsis
dsp
resample
Package resample is a pure-Go streaming sample rate converter.
Package resample is a pure-Go streaming sample rate converter.
backend/aifc/float80
Package float80 implements the 80-bit IEEE 754 extended precision floating- point format.
Package float80 implements the 80-bit IEEE 754 extended precision floating- point format.

Jump to

Keyboard shortcuts

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