wav

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 11 Imported by: 7 modules, 4 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

wav

Go Reference Go Report Card

A Go package for encoding and decoding WAV audio files. Supports PCM integer (8/16/24/32-bit) and IEEE float (32/64-bit) formats, metadata (LIST/INFO chunks), sampler info (smpl chunks), and cue points.

Note: This repository is a fork from go-audio/wav

Installation

go get github.com/cwbudde/wav

Features

  • Decode WAV files into audio.Float32Buffer (via go-audio/audio)
  • Encode audio.Float32Buffer data into valid WAV files
  • Read and write LIST/INFO metadata (artist, title, genre, comments, etc.)
  • Read sampler information (loops, MIDI note, SMPTE offset)
  • Read cue points
  • Streaming decoding with PCMBuffer for memory-efficient processing
  • Rewind support for looped playback

Usage

Decoding a WAV file
file, err := os.Open("input.wav")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

decoder := wav.NewDecoder(file)
buf, err := decoder.FullPCMBuffer()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("%d channels, %d Hz, %d-bit\n",
    decoder.NumChans, decoder.SampleRate, decoder.BitDepth)
fmt.Printf("%d samples decoded\n", len(buf.Data))
Streaming decode (memory-efficient)
decoder := wav.NewDecoder(file)

buf := &audio.Float32Buffer{Data: make([]float32, 4096)}
for {
    n, err := decoder.PCMBuffer(buf)
    if n == 0 {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    // process buf.Data[:n]
}
Encoding a WAV file
out, err := os.Create("output.wav")
if err != nil {
    log.Fatal(err)
}
defer out.Close()

encoder := wav.NewEncoder(out, 44100, 16, 2, 1) // sampleRate, bitDepth, channels, PCM format
if err := encoder.Write(buf); err != nil {
    log.Fatal(err)
}
if err := encoder.Close(); err != nil {
    log.Fatal(err)
}
Reading metadata
decoder := wav.NewDecoder(file)
decoder.ReadMetadata()

if decoder.Metadata != nil {
    fmt.Println("Artist:", decoder.Metadata.Artist)
    fmt.Println("Title:", decoder.Metadata.Title)
    fmt.Println("Genre:", decoder.Metadata.Genre)
}
Writing metadata
encoder := wav.NewEncoder(out, 44100, 16, 2, 1)
encoder.Metadata = &wav.Metadata{
    Artist: "Artist Name",
    Title:  "Track Title",
    Genre:  "Electronic",
}
encoder.Write(buf)
encoder.Close()

CLI Tools

The cmd/ directory contains several command-line utilities:

Tool Description
cmd/metadata Read and display metadata from a WAV file
cmd/wavtoaiff Convert a WAV file to AIFF format
cmd/wavtagger Tag WAV files with metadata (single file or batch)
cmd/gen-sine Generate a sine wave WAV file at a given frequency
Examples
# Read metadata
go run ./cmd/metadata fixtures/listinfo.wav

# Convert WAV to AIFF
go run ./cmd/wavtoaiff -path input.wav

# Tag a WAV file
go run ./cmd/wavtagger -file input.wav -artist "Name" -title "Song"

# Tag all WAV files in a directory
go run ./cmd/wavtagger -dir ./samples -genre "Drums" -regexp 'kit_\d+_(.*)'

# Generate a 440 Hz sine wave (5 seconds)
go run ./cmd/gen-sine -output sine.wav -frequency 440 -length 5

Supported Metadata Fields

The Metadata struct supports standard LIST/INFO chunk fields:

Artist, Title, Comments, Copyright, CreationDate, Engineer, Technician, Genre, Keywords, Medium, Product (album), Subject, Software, Source, Location, TrackNbr

Additionally, SamplerInfo provides MIDI and loop metadata from the smpl chunk.

API Documentation

See the full API reference on pkg.go.dev.

Round-trip APIs

For metadata/chunk-preserving workflows, the decoder and encoder now expose:

  • FormatChunk() *FmtChunk
  • RawChunks() []RawChunk
  • SetRawChunks([]RawChunk)

These methods are additive and coexist with existing fields/methods for backward compatibility.

Documentation

Overview

Package wav provides WAV encoding and decoding utilities for Go.

The package supports PCM integer (8/16/24/32-bit), IEEE float (32/64-bit), A-law, mu-law, and GSM 6.10 decode paths. It also parses and encodes common WAV metadata chunks, including LIST/INFO, cue/smpl, bext, and cart.

For chunk-preserving round-trip workflows, Decoder and Encoder expose additive APIs:

  • FormatChunk() *FmtChunk
  • RawChunks() []RawChunk
  • SetRawChunks([]RawChunk)

Existing Decoder/Encoder fields and methods remain supported for backward compatibility.

Index

Examples

Constants

View Source
const MaxMetadataChunkBytes = 16 << 20

MaxMetadataChunkBytes bounds allocations from untrusted metadata chunk sizes. Applications may impose smaller limits before using the standalone decoders.

Variables

View Source
var (
	// ErrCuePointIDNotFound is returned when a cue point ID cannot be read.
	ErrCuePointIDNotFound = errors.New("failed to read the cue point ID")
	// ErrDataChunkIDNotFound is returned when a data chunk ID cannot be read.
	ErrDataChunkIDNotFound = errors.New("failed to read the data chunk id")
)
View Source
var (
	// CIDList is the chunk ID for a LIST chunk.
	CIDList = [4]byte{'L', 'I', 'S', 'T'}
	// CIDSmpl is the chunk ID for a smpl chunk.
	CIDSmpl = [4]byte{'s', 'm', 'p', 'l'}
	// CIDINFO is the chunk ID for an INFO chunk.
	CIDInfo = []byte{'I', 'N', 'F', 'O'}
	// CIDCue is the chunk ID for the cue chunk.
	CIDCue = [4]byte{'c', 'u', 'e', 0x20}
	// CIDFact is the chunk ID for the fact chunk.
	CIDFact = [4]byte{'f', 'a', 'c', 't'}
	// CIDBext is the chunk ID for the broadcast extension chunk.
	CIDBext = [4]byte{'b', 'e', 'x', 't'}
	// CIDCart is the chunk ID for the cart chunk.
	CIDCart = [4]byte{'c', 'a', 'r', 't'}

	// ErrPCMDataNotFound is returned when PCM data chunk is not found.
	ErrPCMDataNotFound = errors.New("PCM data not found")
	// ErrDurationNilPointer is returned when calculating duration on a nil decoder.
	ErrDurationNilPointer = errors.New("can't calculate the duration of a nil pointer")
	// ErrUnsupportedCompressedFormat is returned when a compressed audio format
	// (e.g. GSM 6.10, TrueSpeech, Voxware) is encountered that has no decoder
	// implementation. The WAV file structure is valid but the audio codec is not
	// supported.
	ErrUnsupportedCompressedFormat = errors.New("unsupported compressed audio format")
)
View Source
var ErrPCMChunkNotFound = errors.New("PCM Chunk not found in audio file")

ErrPCMChunkNotFound indicates a bad audio file without data.

Functions

func DecodeAssociatedDataChunk added in v0.1.2

func DecodeAssociatedDataChunk(decoder *Decoder, chunk *riff.Chunk) error

DecodeAssociatedDataChunk decodes bounded LIST/adtl metadata independently of the audio decoder cursor. It publishes no partial records on malformed input. Multiple adtl lists append their records, independently of cue order.

func DecodeBroadcastChunk

func DecodeBroadcastChunk(dec *Decoder, chnk *riff.Chunk) error

DecodeBroadcastChunk decodes a bext chunk into decoder metadata.

func DecodeCartChunk

func DecodeCartChunk(dec *Decoder, chnk *riff.Chunk) error

DecodeCartChunk decodes a cart chunk into decoder metadata.

func DecodeCueChunk

func DecodeCueChunk(decoder *Decoder, chunk *riff.Chunk) error

DecodeCueChunk decodes a bounded cue payload independently of the audio cursor. Invalid counts/truncated rows never publish partially decoded cues.

func DecodeListChunk

func DecodeListChunk(decoder *Decoder, chunk *riff.Chunk) error

DecodeListChunk decodes a LIST chunk.

func DecodeSamplerChunk

func DecodeSamplerChunk(d *Decoder, ch *riff.Chunk) error

DecodeSamplerChunk decodes a smpl chunk and put the data in Decoder.Metadata.SamplerInfo.

Types

type AssociatedData added in v0.1.2

type AssociatedData struct {
	Labels  []CueLabel
	Notes   []CueLabel
	Regions []CueRegion
	// UnknownSubchunks preserves unrecognized adtl records in encounter order.
	UnknownSubchunks []RawChunk
}

AssociatedData represents a LIST/adtl associated-data list. Cue references are preserved even when this list precedes cue points in the file.

type BroadcastExtension

type BroadcastExtension struct {
	Description         string
	Originator          string
	OriginatorReference string
	OriginationDate     string
	OriginationTime     string
	TimeReference       uint64
	Version             uint16
	UMID                [64]byte
	Reserved            []byte
	CodingHistory       string
}

BroadcastExtension represents metadata stored in the BWF bext chunk.

type Cart

type Cart struct {
	Version            string
	Title              string
	Artist             string
	CutID              string
	ClientID           string
	Category           string
	Classification     string
	OutCue             string
	StartDate          string
	StartTime          string
	EndDate            string
	EndTime            string
	ProducerAppID      string
	ProducerAppVersion string
	UserDef            string
	LevelReference     int32
	PostTimer          [8]uint32
	Reserved           []byte
	URL                string
	TagText            string
}

Cart represents practical fields from the cart chunk.

type ChunkHandler

type ChunkHandler interface {
	CanHandle(chunkID [4]byte, listType [4]byte) bool
	Decode(d *Decoder, ch *riff.Chunk) error
	Encode(e *Encoder) error
}

ChunkHandler is a typed handler for RIFF/WAV chunks. Encode is optional and may return errChunkEncodeNotSupported.

type ChunkRegistry

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

ChunkRegistry resolves chunks to handlers.

func (*ChunkRegistry) Decode

func (r *ChunkRegistry) Decode(dec *Decoder, chnk *riff.Chunk) (bool, error)

Decode dispatches a chunk to the first matching handler.

func (*ChunkRegistry) Register

func (r *ChunkRegistry) Register(handler ChunkHandler)

Register appends a handler to the registry.

type CueLabel added in v0.1.2

type CueLabel struct {
	CuePointID uint32
	Text       string
}

CueLabel is a labl or note record. Text excludes the terminating NUL byte.

type CuePoint

type CuePoint struct {
	ID [4]byte
	// Position is the play-list sample position; zero when no play list exists.
	Position     uint32
	DataChunkID  [4]byte
	ChunkStart   uint32
	BlockStart   uint32
	SampleOffset uint32
}

CuePoint identifies a noteworthy sample position. For ordinary PCM/IEEE WAV, DataChunkID is "data", ChunkStart/BlockStart are zero, and SampleOffset is a sample-frame offset (not a byte or interleaved-channel sample offset).

type CueRegion added in v0.1.2

type CueRegion struct {
	CuePointID   uint32
	SampleLength uint32
	PurposeID    [4]byte
	Country      uint16
	Language     uint16
	Dialect      uint16
	CodePage     uint16
	Text         string
}

CueRegion is an ltxt record describing a sample-frame length at its cue. PurposeID and locale/code-page fields are retained without interpretation.

type Decoder

type Decoder struct {
	NumChans   uint16
	BitDepth   uint16
	SampleRate uint32

	AvgBytesPerSec uint32
	WavAudioFormat uint16
	FmtChunk       *FmtChunk

	PCMSize int

	// pcmChunk is available so we can use the LimitReader
	PCMChunk *riff.Chunk
	// Metadata for the current file
	Metadata *Metadata
	// UnknownChunks stores non-core chunks for optional round-trip writing.
	UnknownChunks []RawChunk
	// CompressedSamples stores the sample count from the fact chunk for
	// compressed formats (diagnostic/informational only).
	CompressedSamples uint32
	// contains filtered or unexported fields
}

Decoder handles the decoding of wav files.

func NewDecoder

func NewDecoder(r io.ReadSeeker) *Decoder

NewDecoder creates a decoder for the passed wav reader. Note that the reader doesn't get rewinded as the container is processed.

func (*Decoder) Duration

func (d *Decoder) Duration() (time.Duration, error)

Duration returns the time duration for the current audio container.

Example
file, err := os.Open("fixtures/kick.wav")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

dur, err := NewDecoder(file).Duration()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("%s duration: %s\n", file.Name(), dur)
Output:
fixtures/kick.wav duration: 204.172335ms

func (*Decoder) EOF

func (d *Decoder) EOF() bool

EOF returns positively if the underlying reader reached the end of file.

func (*Decoder) Err

func (d *Decoder) Err() error

Err returns the first non-EOF error that was encountered by the Decoder.

func (*Decoder) Format

func (d *Decoder) Format() *audio.Format

Format returns the audio format of the decoded content.

func (*Decoder) FormatChunk

func (d *Decoder) FormatChunk() *FmtChunk

FormatChunk returns a copy of the parsed fmt chunk, if available.

func (*Decoder) FullPCMBuffer

func (d *Decoder) FullPCMBuffer() (*audio.Float32Buffer, error)

FullPCMBuffer is an inefficient way to access all the PCM data contained in the audio container. The entire PCM data is held in memory. Consider using PCMBuffer() instead.

func (*Decoder) FwdToPCM

func (d *Decoder) FwdToPCM() error

FwdToPCM forwards the underlying reader until the start of the PCM chunk. If the PCM chunk was already read, no data will be found (you need to rewind).

func (*Decoder) IsValidFile

func (d *Decoder) IsValidFile() bool

IsValidFile verifies that the file is valid/readable.

Example
file, err := os.Open("fixtures/kick.wav")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

fmt.Printf("is this file valid: %t", NewDecoder(file).IsValidFile())
Output:
is this file valid: true

func (*Decoder) NextChunk

func (d *Decoder) NextChunk() (*riff.Chunk, error)

NextChunk returns the next available chunk.

func (*Decoder) PCMBuffer

func (d *Decoder) PCMBuffer(buf *audio.Float32Buffer) (n int, err error)

PCMBuffer populates the passed PCM buffer.

func (*Decoder) PCMLen

func (d *Decoder) PCMLen() int64

PCMLen returns the total number of bytes in the PCM data chunk.

func (*Decoder) RawChunks

func (d *Decoder) RawChunks() []RawChunk

RawChunks returns a copy of preserved non-core chunks.

func (*Decoder) ReadInfo

func (d *Decoder) ReadInfo()

ReadInfo reads the underlying reader until the comm header is parsed. This method is safe to call multiple times.

func (*Decoder) ReadMetadata

func (d *Decoder) ReadMetadata()

ReadMetadata parses the file for extra metadata such as the INFO list chunk. The entire file will be read and should be rewinded if more data must be accessed.

Example
file, err := os.Open("fixtures/listinfo.wav")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

decoder := NewDecoder(file)
decoder.ReadMetadata()

if err := decoder.Err(); err != nil {
	log.Fatal(err)
}

if decoder.Metadata == nil {
	fmt.Println("No metadata found")
	return
}

fmt.Printf("Artist: %s\n", decoder.Metadata.Artist)
fmt.Printf("Title:  %s\n", decoder.Metadata.Title)
fmt.Printf("Album:  %s\n", decoder.Metadata.Product)
fmt.Printf("Track:  %s\n", decoder.Metadata.TrackNbr)
Output:
Artist: artist
Title:  track title
Album:  album title
Track:  42

func (*Decoder) Rewind

func (d *Decoder) Rewind() error

Rewind allows the decoder to be rewound to the beginning of the PCM data. This is useful if you want to keep on decoding the same file in a loop.

func (*Decoder) SampleBitDepth

func (d *Decoder) SampleBitDepth() int32

SampleBitDepth returns the bit depth encoding of each sample.

func (*Decoder) Seek

func (d *Decoder) Seek(offset int64, whence int) (int64, error)

Seek provides access to the cursor position in the PCM data.

func (*Decoder) SetRawChunks

func (d *Decoder) SetRawChunks(chunks []RawChunk)

SetRawChunks replaces preserved non-core chunks with the provided set.

func (*Decoder) String

func (d *Decoder) String() string

String implements the Stringer interface.

func (*Decoder) WasPCMAccessed

func (d *Decoder) WasPCMAccessed() bool

WasPCMAccessed returns positively if the PCM data was previously accessed.

type Encoder

type Encoder struct {
	SampleRate int
	BitDepth   int
	NumChans   int

	// A number indicating the WAVE format category of the file. The content of
	// the <format-specific-fields> portion of the ‘fmt’ chunk, and the
	// interpretation of the waveform data, depend on this value. PCM = 1 (i.e.
	// Linear quantization) Values other than 1 indicate some form of
	// compression.
	WavAudioFormat int
	// FmtChunk optionally controls fmt chunk serialization, including
	// WAVE_FORMAT_EXTENSIBLE fields.
	FmtChunk *FmtChunk

	// Metadata contains metadata to inject in the file.
	Metadata *Metadata
	// UnknownChunks contains non-core chunks to preserve on write.
	UnknownChunks []RawChunk

	WrittenBytes int
	// contains filtered or unexported fields
}

Encoder encodes LPCM data into a wav containter.

func NewEncoder

func NewEncoder(w io.WriteSeeker, sampleRate, bitDepth, numChans, audioFormat int) *Encoder

NewEncoder creates a new encoder to create a new wav file. Don't forget to add Frames to the encoder before writing. Its temporary sample buffer is allocated lazily on the first Write.

func NewEncoderFromDecoder

func NewEncoderFromDecoder(w io.WriteSeeker, dec *Decoder) *Encoder

NewEncoderFromDecoder creates an encoder initialized from decoder settings. It carries format details and preserved unknown chunks for round-trip flows.

func (*Encoder) AddBE

func (e *Encoder) AddBE(src any) error

AddBE serializes and adds the passed value using big endian.

func (*Encoder) AddLE

func (e *Encoder) AddLE(src any) error

AddLE serializes and adds the passed value using little endian.

func (*Encoder) Close

func (e *Encoder) Close() error

Close flushes the content to disk, make sure the headers are up to date Note that the underlying writer is NOT being closed.

func (*Encoder) FormatChunk

func (e *Encoder) FormatChunk() *FmtChunk

FormatChunk returns a copy of the configured fmt chunk, if available.

func (*Encoder) RawChunks

func (e *Encoder) RawChunks() []RawChunk

RawChunks returns a copy of configured non-core chunks.

func (*Encoder) SetRawChunks

func (e *Encoder) SetRawChunks(chunks []RawChunk)

SetRawChunks replaces configured non-core chunks with the provided set.

func (*Encoder) Write

func (e *Encoder) Write(buf *audio.Float32Buffer) error

Write encodes and writes the passed buffer to the underlying writer. Don't forget to Close() the encoder or the file won't be valid.

Example
file, err := os.Open("fixtures/kick.wav")
if err != nil {
	panic(fmt.Sprintf("couldn't open audio file - %v", err))
}

// Decode the original audio file
// and collect audio content and information.
decoder := NewDecoder(file)

buf, err := decoder.FullPCMBuffer()
if err != nil {
	panic(err)
}

file.Close()
fmt.Println("Old file ->", decoder)

// Destination file
out, err := os.Create("testOutput/kick.wav")
if err != nil {
	panic(fmt.Sprintf("couldn't create output file - %v", err))
}

// setup the encoder and write all the frames
encoder := NewEncoder(out,
	buf.Format.SampleRate,
	int(decoder.BitDepth),
	buf.Format.NumChannels,
	int(decoder.WavAudioFormat))
if err = encoder.Write(buf); err != nil {
	panic(err)
}
// close the encoder to make sure the headers are properly
// set and the data is flushed.
if err = encoder.Close(); err != nil {
	panic(err)
}

out.Close()

// reopen to confirm things worked well
out, err = os.Open("testOutput/kick.wav")
if err != nil {
	panic(err)
}

d2 := NewDecoder(out)
d2.ReadInfo()
fmt.Println("New file ->", d2)
out.Close()
os.Remove(out.Name())
Output:
Old file -> Format: WAVE - 1 channels @ 22050 / 16 bits - Duration: 0.204172 seconds
New file -> Format: WAVE - 1 channels @ 22050 / 16 bits - Duration: 0.204172 seconds

func (*Encoder) WriteFrame

func (e *Encoder) WriteFrame(value any) error

WriteFrame writes a single frame of data to the underlying writer.

func (*Encoder) WriteInt added in v0.1.3

func (e *Encoder) WriteInt(buf *audio.IntBuffer) error

WriteInt writes interleaved signed PCM integer codes without converting them through floating point. The encoder must select PCM at 8, 16, 24 or 32 bits; every code must be in that depth's signed range. In particular, 8-bit caller codes are [-128,127] and are serialized with the WAV unsigned offset of 128. Format must match the encoder's channel count and sample rate, and Data must contain whole frames. SourceBitDepth may be zero (unspecified) or match the encoder's BitDepth. Empty buffers emit a valid empty data chunk.

All input validation precedes header/sample writes and leaves encoder state unchanged on rejection. I/O failures may have written partial data. Successful calls consume but do not retain or modify Data, reuse the encoder's byte scratch, and can be interleaved with Write calls. Call Close to finish RIFF sizes, padding and metadata. Writes after Close are rejected.

Example
writer := new(intMemoryWriter)

encoder := NewEncoder(writer, 48000, 32, 1, wavFormatPCM)
if err := encoder.WriteInt(&audio.IntBuffer{Format: &audio.Format{SampleRate: 48000, NumChannels: 1}, SourceBitDepth: 32, Data: []int{16777217, -16777217}}); err != nil {
	panic(err)
}

if err := encoder.Close(); err != nil {
	panic(err)
}

fmt.Printf("%x\n", writer.data[44:52])
Output:
01000001fffffffe

type FmtChunk

type FmtChunk struct {
	FormatTag      uint16
	NumChannels    uint16
	SampleRate     uint32
	AvgBytesPerSec uint32
	BlockAlign     uint16
	BitsPerSample  uint16
	ExtraData      []byte
	Extensible     *FmtExtensible
}

FmtChunk stores the parsed WAV fmt chunk, including extensible metadata.

func (*FmtChunk) Clone

func (f *FmtChunk) Clone() *FmtChunk

func (*FmtChunk) EffectiveFormatTag

func (f *FmtChunk) EffectiveFormatTag() uint16

type FmtExtensible

type FmtExtensible struct {
	ValidBitsPerSample uint16
	ChannelMask        uint32
	SubFormat          [16]byte
	ExtraData          []byte
}

FmtExtensible stores WAVE_FORMAT_EXTENSIBLE extra fields.

type Metadata

type Metadata struct {
	SamplerInfo *SamplerInfo
	// BroadcastExtension stores BWF bext metadata.
	BroadcastExtension *BroadcastExtension
	// Cart stores cart chunk metadata used in radio automation workflows.
	Cart *Cart
	// Artist of the original subject of the file. For example, Michaelangelo.
	Artist string
	// Comments provides general comments about the file or the subject of the
	// file. If the comment is several sentences long, end each sentence with a
	// period. Do not include newline characters.
	Comments string
	// Copyright records the copyright information for the file.
	Copyright string
	// CreationDate specifies the date the subject of the file was created. List
	// dates in year-month-day format, padding one-digit months and days with a
	// zero on the left. For example: 1553-05-03 for May 3, 1553. The year
	// should always be given using four digits.
	CreationDate string
	// Engineer stores the name of the engineer who worked on the file. If there
	// are multiple engineers, separate the names by a semicolon and a blank.
	// For example: Smith, John; Adams, Joe.
	Engineer string
	// Technician identifies the technician who sampled the subject file. For
	// example: Smith, John.
	Technician string
	// Genre describes the original work, such as jazz, classical, rock, etc.
	Genre string
	// Keywords provides a list of keywords that refer to the file or subject of
	// the file. Separate multiple keywords with a semicolon and a blank. For
	// example, Seattle; zoology; The Civil War.
	Keywords string
	// Medium describes the original subject of the file, such as record, CD and so forth.
	Medium string
	// Title stores the title of the subject of the file, such as bohemian rhapsody.
	Title string
	// Product AKA album specifies the name of the title the file was originally
	// intended for: A Night at the Opera
	Product string
	// Subject describes the contents of the file, such as Metadata Management.
	Subject string
	// Software identifies the name of the software package used to create the
	// file, such as go-audio.
	Software string
	// Source identifies the name of the person or organization who supplied the
	// original subject of the file. For example: Splice.
	Source string
	// Location or Archival Location - Indicates where the subject of the file is archived.
	Location string
	// TrackNbr is the track number
	TrackNbr string
	// CuePoints is a list of cue points in the wav file.
	CuePoints []*CuePoint
	// AssociatedData stores labels, notes and region lengths from LIST/adtl.
	AssociatedData *AssociatedData
}

Metadata represents optional metadata added to the wav file.

type RawChunk

type RawChunk struct {
	ID [4]byte
	// Size mirrors len(Data) for preserved chunks.
	Size uint32
	Data []byte
	// Order is the original chunk order index encountered during decode.
	Order int
	// BeforeData indicates if this chunk appeared before the data chunk.
	BeforeData bool
}

RawChunk stores a non-core RIFF/WAV chunk for round-trip preservation.

func EncodeAssociatedDataChunk added in v0.1.2

func EncodeAssociatedDataChunk(a *AssociatedData) (RawChunk, error)

EncodeAssociatedDataChunk serializes an adtl list into a bounded RIFF payload. The returned chunk can be measured and passed to Encoder.SetRawChunks.

func EncodeCueChunk added in v0.1.2

func EncodeCueChunk(cues []*CuePoint) (RawChunk, error)

EncodeCueChunk serializes cue points into a RIFF payload without writing a file. The returned chunk can be measured and passed to Encoder.SetRawChunks. An empty slice encodes a valid zero-count cue chunk; nil rows are rejected.

func (RawChunk) Clone

func (c RawChunk) Clone() RawChunk

type SampleLoop

type SampleLoop struct {
	// CuePointID - The Cue Point ID specifies the unique ID that corresponds to one of the
	// defined cue points in the cue point list. Furthermore, this ID
	// corresponds to any labels defined in the associated data list chunk which
	// allows text labels to be assigned to the various sample loops.
	CuePointID [4]byte
	// Type - The type field defines how the waveform samples will be looped.
	// 0 Loop forward (normal)
	// 1 Alternating loop (forward/backward, also known as Ping Pong)
	// 2 Loop backward (reverse)
	// 3 Reserved for future standard types
	// 32 - 0xFFFFFFFF Sampler specific types (defined by manufacturer)
	Type uint32
	// Start - The start value specifies the byte offset into the waveform data
	// of the first sample to be played in the loop.
	Start uint32
	// End - The end value specifies the byte offset into the waveform data of
	// the last sample to be played in the loop.
	End uint32
	// Fraction - The fractional value specifies a fraction of a sample at which
	// to loop. This allows a loop to be fine tuned at a resolution greater than
	// one sample. The value can range from 0x00000000 to 0xFFFFFFFF. A value of
	// 0 means no fraction, a value of 0x80000000 means 1/2 of a sample length.
	// 0xFFFFFFFF is the smallest fraction of a sample that can be represented.
	Fraction uint32
	// PlayCount - The play count value determines the number of times to play
	// the loop. A value of 0 specifies an infinite sustain loop. An infinite
	// sustain loop will continue looping until some external force interrupts
	// playback, such as the musician releasing the key that triggered the
	// wave's playback. All other values specify an absolute number of times to
	// loop.
	PlayCount uint32
}

SampleLoop indicates a loop and its properties within the audio file.

type SamplerInfo

type SamplerInfo struct {
	// Manufacturer field specifies the MIDI Manufacturer's Association
	// (MMA) Manufacturer code for the sampler intended to receive this file's
	// waveform. Each manufacturer of a MIDI product is assigned a unique ID
	// which identifies the company. If no particular manufacturer is to be
	// specified, a value of 0 should be used. The value is stored with some
	// extra information to enable translation to the value used in a MIDI
	// System Exclusive transmission to the sampler. The high byte indicates the
	// number of low order bytes (1 or 3) that are valid for the manufacturer
	// code. For example, the value for Digidesign will be 0x01000013 (0x13) and
	// the value for Microsoft will be 0x30000041 (0x00, 0x00, 0x41).
	Manufacturer [4]byte
	// Product field specifies the MIDI model ID defined by the manufacturer
	// corresponding to the Manufacturer field. Contact the manufacturer of the
	// sampler to get the model ID. If no particular manufacturer's product is
	// to be specified, a value of 0 should be used.
	Product [4]byte
	// SamplePeriod The sample period specifies the duration of time that passes
	// during the playback of one sample in nanoseconds (normally equal to 1 /
	// Samplers Per Second, where Samples Per Second is the value found in the
	// format chunk).
	SamplePeriod uint32
	// MIDIUnityNote The MIDI unity note value has the same meaning as the instrument chunk's
	// MIDI Unshifted Note field which specifies the musical note at which the
	// sample will be played at it's original sample rate (the sample rate
	// specified in the format chunk).
	MIDIUnityNote uint32
	// MIDIPitchFraction The MIDI pitch fraction specifies the fraction of a
	// semitone up from the specified MIDI unity note field. A value of
	// 0x80000000 means 1/2 semitone (50 cents) and a value of 0x00000000 means
	// no fine tuning between semitones.
	MIDIPitchFraction uint32
	// SMPTEFormat The SMPTE format specifies the Society of Motion Pictures and
	// Television E time format used in the following SMPTE Offset field. If a
	// value of 0 is set, SMPTE Offset should also be set to 0. (0, 24, 25, 29, 30)
	SMPTEFormat uint32
	// SMPTEOffset The SMPTE Offset value specifies the time offset to be used
	// for the synchronization / calibration to the first sample in the
	// waveform. This value uses a format of 0xhhmmssff where hh is a signed
	// value that specifies the number of hours (-23 to 23), mm is an unsigned
	// value that specifies the number of minutes (0 to 59), ss is an unsigned
	// value that specifies the number of seconds (0 to 59) and ff is an
	// unsigned value that specifies the number of frames (0 to -1).
	SMPTEOffset uint32
	// NumSampleLoops The sample loops field specifies the number Sample Loop
	// definitions in the following list. This value may be set to 0 meaning
	// that no sample loops follow.
	NumSampleLoops uint32
	// Loops A list of sample loops is simply a set of consecutive loop
	// descriptions. The sample loops do not have to be in any particular order
	// because each sample loop associated cue point position is used to
	// determine the play order.
	Loops []*SampleLoop
}

SamplerInfo is extra metadata pertinent to a sampler type usage.

Directories

Path Synopsis
cmd
gen-sine command
metadata command
This tool reads metadata from the passed wav file if available.
This tool reads metadata from the passed wav file if available.
wavtagger command
This command line tool helps the user tag wav files by injecting metadata in the file in a safe way.
This command line tool helps the user tag wav files by injecting metadata in the file in a safe way.
wavtoaiff command
This tool converts an aiff file into an identical wav file and stores it in the same folder as the source.
This tool converts an aiff file into an identical wav file and stores it in the same folder as the source.

Jump to

Keyboard shortcuts

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