alsa

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: BSD-3-Clause Imports: 14 Imported by: 0

README

ALSA

Status Go Reference

Go reimplementation of tinyalsa library.

This library provides a Go interface to the Linux ALSA for interacting with sound card devices, allowing for raw audio (PCM) playback and capture, and control over mixer elements like volume and switches.

Usage

See utils for usage examples.

Testing

Running the tests requires specific kernel modules to create virtual sound card devices for playback, capture, and mixer control tests without needing physical hardware:

  • snd-dummy: Creates a virtual sound card with a mixer, used for testing control functionality.
  • snd-aloop: Creates a loopback sound card, allowing playback data to be captured, which is essential for testing PCM I/O.

You can load them with the following commands:

sudo modprobe snd-dummy
sudo modprobe snd-aloop

Documentation

Overview

Package alsa provides a Go interface to the Linux ALSA subsystem, modeled after the tinyalsa library.

Index

Constants

View Source
const (
	SNDRV_PCM_INTERVAL_OPENMIN = 1 << 0
	SNDRV_PCM_INTERVAL_OPENMAX = 1 << 1
	SNDRV_PCM_INTERVAL_INTEGER = 1 << 2
	SNDRV_PCM_INTERVAL_EMPTY   = 1 << 3
)

Constants for the bitfields within snd_interval.flags to match C enum.

View Source
const (
	SNDRV_PCM_MMAP_OFFSET_STATUS  = 0x80000000
	SNDRV_PCM_MMAP_OFFSET_CONTROL = 0x81000000
)

ALSA MMAP offsets for status and control pages.

View Source
const (
	SNDRV_PCM_SYNC_PTR_APPL      = 1 << 0
	SNDRV_PCM_SYNC_PTR_AVAIL_MIN = 1 << 2
	SNDRV_PCM_SYNC_PTR_HWSYNC    = 1 << 1
)

Variables

View Source
var (
	// PCM IOCTLs
	SNDRV_PCM_IOCTL_HW_REFINE     uintptr
	SNDRV_PCM_IOCTL_HW_PARAMS     uintptr
	SNDRV_PCM_IOCTL_SW_PARAMS     uintptr
	SNDRV_PCM_IOCTL_INFO          uintptr
	SNDRV_PCM_IOCTL_PAUSE         uintptr
	SNDRV_PCM_IOCTL_RESUME        uintptr
	SNDRV_PCM_IOCTL_PREPARE       uintptr
	SNDRV_PCM_IOCTL_START         uintptr
	SNDRV_PCM_IOCTL_DROP          uintptr
	SNDRV_PCM_IOCTL_DRAIN         uintptr
	SNDRV_PCM_IOCTL_DELAY         uintptr
	SNDRV_PCM_IOCTL_LINK          uintptr
	SNDRV_PCM_IOCTL_UNLINK        uintptr
	SNDRV_PCM_IOCTL_HWSYNC        uintptr
	SNDRV_PCM_IOCTL_SYNC_PTR      uintptr
	SNDRV_PCM_IOCTL_TTSTAMP       uintptr
	SNDRV_PCM_IOCTL_WRITEI_FRAMES uintptr
	SNDRV_PCM_IOCTL_READI_FRAMES  uintptr
	SNDRV_PCM_IOCTL_WRITEN_FRAMES uintptr
	SNDRV_PCM_IOCTL_READN_FRAMES  uintptr
	SNDRV_PCM_IOCTL_STATUS        uintptr

	// Control IOCTLs
	SNDRV_CTL_IOCTL_CARD_INFO        uintptr
	SNDRV_CTL_IOCTL_ELEM_LIST        uintptr
	SNDRV_CTL_IOCTL_ELEM_INFO        uintptr
	SNDRV_CTL_IOCTL_ELEM_READ        uintptr
	SNDRV_CTL_IOCTL_ELEM_WRITE       uintptr
	SNDRV_CTL_IOCTL_SUBSCRIBE_EVENTS uintptr
	SNDRV_CTL_IOCTL_TLV_READ         uintptr
	SNDRV_CTL_IOCTL_TLV_WRITE        uintptr
)
View Source
var PcmParamAccessNames = []string{
	"MMAP_INTERLEAVED",
	"MMAP_NONINTERLEAVED",
	"MMAP_COMPLEX",
	"RW_INTERLEAVED",
	"RW_NONINTERLEAVED",
}

PcmParamAccessNames provides human-readable names for PCM access types. The index corresponds to the SNDRV_PCM_ACCESS_* value.

View Source
var PcmParamFormatNames = map[PcmFormat]string{
	PCM_FORMAT_S8:                 "S8",
	PCM_FORMAT_U8:                 "U8",
	PCM_FORMAT_S16_LE:             "S16_LE",
	PCM_FORMAT_S16_BE:             "S16_BE",
	PCM_FORMAT_U16_LE:             "U16_LE",
	PCM_FORMAT_U16_BE:             "U16_BE",
	PCM_FORMAT_S24_LE:             "S24_LE",
	PCM_FORMAT_S24_BE:             "S24_BE",
	PCM_FORMAT_U24_LE:             "U24_LE",
	PCM_FORMAT_U24_BE:             "U24_BE",
	PCM_FORMAT_S32_LE:             "S32_LE",
	PCM_FORMAT_S32_BE:             "S32_BE",
	PCM_FORMAT_U32_LE:             "U32_LE",
	PCM_FORMAT_U32_BE:             "U32_BE",
	PCM_FORMAT_FLOAT_LE:           "FLOAT_LE",
	PCM_FORMAT_FLOAT_BE:           "FLOAT_BE",
	PCM_FORMAT_FLOAT64_LE:         "FLOAT64_LE",
	PCM_FORMAT_FLOAT64_BE:         "FLOAT64_BE",
	PCM_FORMAT_IEC958_SUBFRAME_LE: "IEC958_SUBFRAME_LE",
	PCM_FORMAT_IEC958_SUBFRAME_BE: "IEC958_SUBFRAME_BE",
	PCM_FORMAT_MU_LAW:             "MU_LAW",
	PCM_FORMAT_A_LAW:              "A_LAW",
	PCM_FORMAT_IMA_ADPCM:          "IMA_ADPCM",
	PCM_FORMAT_MPEG:               "MPEG",
	PCM_FORMAT_GSM:                "GSM",
	PCM_FORMAT_SPECIAL:            "SPECIAL",
	PCM_FORMAT_S24_3LE:            "S24_3LE",
	PCM_FORMAT_S24_3BE:            "S24_3BE",
	PCM_FORMAT_U24_3LE:            "U24_3LE",
	PCM_FORMAT_U24_3BE:            "U24_3BE",
	PCM_FORMAT_S20_3LE:            "S20_3LE",
	PCM_FORMAT_S20_3BE:            "S20_3BE",
	PCM_FORMAT_U20_3LE:            "U20_3LE",
	PCM_FORMAT_U20_3BE:            "U20_3BE",
	PCM_FORMAT_S18_3LE:            "S18_3LE",
	PCM_FORMAT_S18_3BE:            "S18_3BE",
	PCM_FORMAT_U18_3LE:            "U18_3LE",
	PCM_FORMAT_U18_3BE:            "U18_3BE",
}

PcmParamFormatNames provides human-readable names for PCM formats. The index corresponds to the PcmFormat (SNDRV_PCM_FORMAT_*) value.

View Source
var PcmParamSubformatNames = []string{
	"STD",
}

PcmParamSubformatNames provides human-readable names for PCM subformats. The index corresponds to the SNDRV_PCM_SUBFORMAT_* value.

Functions

func PcmBytesToFrames

func PcmBytesToFrames(p *PCM, bytes uint32) uint32

PcmBytesToFrames converts a number of bytes to the corresponding number of frames.

func PcmFormatToBits

func PcmFormatToBits(f PcmFormat) uint32

PcmFormatToBits returns the number of bits per sample for a given format. This reflects the space occupied in memory, so 24-bit formats in 32-bit containers return 32.

func PcmFramesToBytes

func PcmFramesToBytes(p *PCM, frames uint32) uint32

PcmFramesToBytes converts a number of frames to the corresponding number of bytes.

Types

type Config

type Config struct {
	Channels         uint32
	Rate             uint32
	PeriodSize       uint32
	PeriodCount      uint32
	Format           PcmFormat
	StartThreshold   uint32
	StopThreshold    uint32
	SilenceThreshold SndPcmUframesT
	SilenceSize      SndPcmUframesT
	AvailMin         uint32
}

Config encapsulates the hardware and software parameters of a PCM stream.

type CtlAccessFlag

type CtlAccessFlag uint32

CtlAccessFlag defines the access permissions for a mixer control.

const (
	// If set, the control is readable.
	SNDRV_CTL_ELEM_ACCESS_READ CtlAccessFlag = 1 << 0
	// If set, the control is writable.
	SNDRV_CTL_ELEM_ACCESS_WRITE CtlAccessFlag = 1 << 1
	// If set, the control uses the TLV mechanism for custom data structures.
	SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE CtlAccessFlag = 1 << 13
)

type Mixer

type Mixer struct {
	Ctls []*MixerCtl
	// contains filtered or unexported fields
}

Mixer represents an open ALSA mixer device handle.

func MixerOpen

func MixerOpen(card uint) (*Mixer, error)

MixerOpen opens the ALSA mixer for a given sound card and enumerates its controls. Note: This implementation does not support the ALSA plugin architecture and will only open direct hardware control devices (e.g., /dev/snd/controlC0).

func (*Mixer) AddNewCtls

func (m *Mixer) AddNewCtls() error

AddNewCtls scans for and adds any new controls that have appeared since the mixer was opened.

func (*Mixer) Close

func (m *Mixer) Close() error

Close closes the mixer device handle.

func (*Mixer) ConsumeEvent

func (m *Mixer) ConsumeEvent() error

ConsumeEvent reads and discards a single pending mixer event.

func (*Mixer) Ctl

func (m *Mixer) Ctl(id uint32) (*MixerCtl, error)

Ctl returns a mixer control by its numeric ID (`numid`).

func (*Mixer) CtlByIndex

func (m *Mixer) CtlByIndex(index uint) (*MixerCtl, error)

CtlByIndex returns a mixer control by its 0-based index in the enumerated list. The index is valid from 0 to NumCtls() - 1.

func (*Mixer) CtlByName

func (m *Mixer) CtlByName(name string) (*MixerCtl, error)

CtlByName returns the first mixer control found with the given name.

func (*Mixer) CtlByNameAndDevice

func (m *Mixer) CtlByNameAndDevice(name string, device uint32) (*MixerCtl, error)

CtlByNameAndDevice returns a mixer control handle by name and device number.

func (*Mixer) CtlByNameAndIndex

func (m *Mixer) CtlByNameAndIndex(name string, index uint) (*MixerCtl, error)

CtlByNameAndIndex returns a specific mixer control handle by name and index.

func (*Mixer) CtlByNameAndSubdevice

func (m *Mixer) CtlByNameAndSubdevice(name string, subdevice uint32) (*MixerCtl, error)

CtlByNameAndSubdevice returns a mixer control handle by name and subdevice number.

func (*Mixer) Fd

func (m *Mixer) Fd() uintptr

Fd returns the underlying file descriptor for the mixer device.

func (*Mixer) Name

func (m *Mixer) Name() string

Name returns the name of the sound card.

func (*Mixer) NumCtls

func (m *Mixer) NumCtls() int

NumCtls returns the total number of controls found on the mixer.

func (*Mixer) NumCtlsByName

func (m *Mixer) NumCtlsByName(name string) int

NumCtlsByName returns the number of controls that match the given name.

func (*Mixer) ReadEvent

func (m *Mixer) ReadEvent() (*MixerEvent, error)

ReadEvent reads a pending mixer event from the device.

func (*Mixer) SubscribeEvents

func (m *Mixer) SubscribeEvents(enable bool) error

SubscribeEvents enables or disables event generation for this mixer handle.

func (*Mixer) WaitEvent

func (m *Mixer) WaitEvent(timeoutMs int) (bool, error)

WaitEvent waits for a mixer event to occur. It returns true if an event is pending, false on timeout.

type MixerCtl

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

MixerCtl represents an individual mixer control handle.

func (*MixerCtl) Access

func (ctl *MixerCtl) Access() uint32

Access returns the control access.

func (*MixerCtl) AllEnumStrings

func (ctl *MixerCtl) AllEnumStrings() ([]string, error)

AllEnumStrings returns a slice containing all possible string values for an enumerated control.

func (*MixerCtl) Array

func (ctl *MixerCtl) Array(array any) error

Array reads the entire multi-value array of a control. `array` must be a pointer to a slice of a type compatible with the control's type:

  • MIXER_CTL_TYPE_BOOL, _INT, _ENUM: *[]int32
  • MIXER_CTL_TYPE_BYTE: *[]byte
  • MIXER_CTL_TYPE_INT64: *[]int64
  • MIXER_CTL_TYPE_IEC958: *[]SndAesEbu (typically only one value)

func (*MixerCtl) Device

func (ctl *MixerCtl) Device() uint32

Device returns the device number associated with the control.

func (*MixerCtl) EnumString

func (ctl *MixerCtl) EnumString(enumID uint) (string, error)

EnumString returns the string associated with an enumerated value.

func (*MixerCtl) EnumValueString

func (ctl *MixerCtl) EnumValueString(index uint) (string, error)

EnumValueString gets the string representation of the currently selected enumerated value. This is a convenience function that combines Value and EnumString.

func (*MixerCtl) ID

func (ctl *MixerCtl) ID() uint32

ID returns the numeric ID (`numid`) of the control.

func (*MixerCtl) IsAccessTLVRw

func (ctl *MixerCtl) IsAccessTLVRw() bool

IsAccessTLVRw checks if the control uses the TLV mechanism for custom data.

func (*MixerCtl) Name

func (ctl *MixerCtl) Name() string

Name returns the name of the control.

func (*MixerCtl) NumEnums

func (ctl *MixerCtl) NumEnums() (uint32, error)

NumEnums returns the number of items for an enumerated control.

func (*MixerCtl) NumValues

func (ctl *MixerCtl) NumValues() uint32

NumValues returns the number of values for the control (e.g., 2 for stereo volume).

func (*MixerCtl) Percent

func (ctl *MixerCtl) Percent(index uint) (int, error)

Percent gets the control's value as a percentage (0-100).

func (*MixerCtl) RangeMax

func (ctl *MixerCtl) RangeMax() (int, error)

RangeMax returns the maximum value for an integer control.

func (*MixerCtl) RangeMax64

func (ctl *MixerCtl) RangeMax64() (int64, error)

RangeMax64 returns the maximum value for an int64 control.

func (*MixerCtl) RangeMin

func (ctl *MixerCtl) RangeMin() (int, error)

RangeMin returns the minimum value for an integer control.

func (*MixerCtl) RangeMin64

func (ctl *MixerCtl) RangeMin64() (int64, error)

RangeMin64 returns the minimum value for an int64 control.

func (*MixerCtl) SetArray

func (ctl *MixerCtl) SetArray(array any) error

SetArray writes an entire multi-value array to a control. `array` must be a slice of a type compatible with the control's type:

  • MIXER_CTL_TYPE_BOOL, _INT, _ENUM: []int32
  • MIXER_CTL_TYPE_BYTE: []byte
  • MIXER_CTL_TYPE_INT64: []int64
  • MIXER_CTL_TYPE_IEC958: []SndAesEbu

func (*MixerCtl) SetEnumByString

func (ctl *MixerCtl) SetEnumByString(value string) error

SetEnumByString sets the value of an enumerated control by its string name.

func (*MixerCtl) SetPercent

func (ctl *MixerCtl) SetPercent(index uint, percent int) error

SetPercent sets the control's value as a percentage (0-100).

func (*MixerCtl) SetValue

func (ctl *MixerCtl) SetValue(index uint, value int) error

SetValue writes a single value to a control at a given index.

func (*MixerCtl) SetValue64

func (ctl *MixerCtl) SetValue64(index uint, value int64) error

SetValue64 writes a single 64-bit integer value to a control at a given index.

func (*MixerCtl) String

func (ctl *MixerCtl) String() string

String returns a human-readable representation of the mixer control's properties and current state.

func (*MixerCtl) Subdevice

func (ctl *MixerCtl) Subdevice() uint32

Subdevice returns the subdevice number associated with the control.

func (*MixerCtl) Type

func (ctl *MixerCtl) Type() MixerCtlType

Type returns the data type of the control's value.

func (*MixerCtl) TypeString

func (ctl *MixerCtl) TypeString() string

TypeString returns a string representation of the control's data type.

func (*MixerCtl) Update

func (ctl *MixerCtl) Update() error

Update refreshes the control's information from the kernel. This is useful for checking for changes to a control's properties (like value ranges) after a mixer event of type SNDRV_CTL_EVENT_MASK_INFO.

func (*MixerCtl) Value

func (ctl *MixerCtl) Value(index uint) (int, error)

Value reads a single value from a control at a given index. This is for controls with types BOOL, INT, ENUM, and BYTE. For INT64 controls, use Value64.

func (*MixerCtl) Value64

func (ctl *MixerCtl) Value64(index uint) (int64, error)

Value64 reads a single 64-bit integer value from a control at a given index.

type MixerCtlType

type MixerCtlType int32

MixerCtlType defines the value type of mixer control.

const (
	MIXER_CTL_TYPE_BOOL    MixerCtlType = 0
	MIXER_CTL_TYPE_INT     MixerCtlType = 1
	MIXER_CTL_TYPE_ENUM    MixerCtlType = 2
	MIXER_CTL_TYPE_BYTE    MixerCtlType = 3
	MIXER_CTL_TYPE_IEC958  MixerCtlType = 4
	MIXER_CTL_TYPE_INT64   MixerCtlType = 5
	MIXER_CTL_TYPE_UNKNOWN MixerCtlType = -1
)

type MixerEvent

type MixerEvent struct {
	Type      MixerEventType
	ControlID uint32 // The numid of the control that changed.
}

MixerEvent represents a notification from the ALSA control interface.

type MixerEventType

type MixerEventType uint32

MixerEventType defines the type of event generated by the mixer.

const (
	SNDRV_CTL_EVENT_ELEM = 0

	// Indicates that a control element's value has changed.
	SNDRV_CTL_EVENT_MASK_VALUE MixerEventType = 1 << 0
	// Indicates that a control element's metadata (e.g., range) has changed.
	SNDRV_CTL_EVENT_MASK_INFO MixerEventType = 1 << 1
	// Indicates that a control element has been added.
	SNDRV_CTL_EVENT_MASK_ADD MixerEventType = 1 << 2
	// Indicates a control element has been removed.
	SNDRV_CTL_EVENT_MASK_REMOVE MixerEventType = 1 << 3
)

type PCM

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

PCM represents an open ALSA PCM device handle.

func PcmOpen

func PcmOpen(card, device uint, flags PcmFlag, config *Config) (*PCM, error)

PcmOpen opens an ALSA PCM device and configures it according to the provided parameters. Note: This implementation does not support the ALSA plugin architecture and will only open direct hardware PCM devices (e.g., /dev/snd/pcmC0D0p).

func PcmOpenByName

func PcmOpenByName(name string, flags PcmFlag, config *Config) (*PCM, error)

PcmOpenByName opens a PCM by its name, in the format "hw:C,D".

func (*PCM) AvailMax

func (p *PCM) AvailMax() (int, error)

AvailMax returns the maximum number of frames that can be written to a playback stream or read from a capture stream. This function is only available for MMAP streams.

func (*PCM) AvailUpdate

func (p *PCM) AvailUpdate() (int, error)

AvailUpdate synchronizes the PCM state with the kernel and returns the number of available frames. For playback streams, this is the number of frames that can be written. For capture streams, this is the number of frames that can be read. This function is only available for MMAP streams.

func (*PCM) BufferSize

func (p *PCM) BufferSize() uint32

BufferSize returns the PCM's total buffer size in frames.

func (*PCM) Channels

func (p *PCM) Channels() uint32

Channels returns the number of channels for the PCM stream.

func (*PCM) Close

func (p *PCM) Close() error

Close closes the PCM device handle and releases all associated resources.

func (*PCM) Config

func (p *PCM) Config() Config

Config returns a copy of the PCM's current configuration.

func (*PCM) Delay

func (p *PCM) Delay() (int, error)

Delay returns the current delay for the PCM stream in frames.

func (*PCM) Drain

func (p *PCM) Drain() error

Drain waits for all pending frames in the buffer to be played. This is a blocking call and only applies to playback streams.

func (*PCM) Error

func (p *PCM) Error() string

Error returns the last error message as a string. This is useful for debugging setup or I/O failures. It is the Go equivalent of pcm_get_error().

func (*PCM) Fd

func (p *PCM) Fd() uintptr

Fd returns the underlying file descriptor for the PCM device.

func (*PCM) Flags

func (p *PCM) Flags() PcmFlag

Flags returns the sample flags of the PCM stream.

func (*PCM) Format

func (p *PCM) Format() PcmFormat

Format returns the sample format of the PCM stream.

func (*PCM) FrameSize

func (p *PCM) FrameSize() uint32

FrameSize returns the size of a single frame in bytes. A frame contains one sample for each channel.

func (*PCM) HWPtr

func (p *PCM) HWPtr() (hwPtr SndPcmUframesT, tstamp time.Time, err error)

HWPtr returns the current hardware pointer position and the corresponding timestamp. This function is only available for MMAP streams.

func (*PCM) IsReady

func (p *PCM) IsReady() bool

IsReady checks if the PCM handle is valid.

func (*PCM) KernelState

func (p *PCM) KernelState() PcmState

KernelState returns the current state of the PCM stream by querying the kernel.

func (p *PCM) Link(other *PCM) error

Link establishes a start/stop synchronization between two PCMs. After this function is called, the two PCMs will prepare, start and stop in sync.

func (*PCM) MmapBegin

func (p *PCM) MmapBegin(wantFrames uint32) (buffer []byte, offsetFrames, actualFrames uint32, err error)

MmapBegin prepares for a memory-mapped transfer. It returns a slice of the main buffer corresponding to the available contiguous space for writing or reading, the offset in frames from the start of the buffer, and the number of frames available in that slice.

func (*PCM) MmapCommit

func (p *PCM) MmapCommit(frames uint32) error

MmapCommit commits the number of frames transferred after a MmapBegin call.

func (*PCM) MmapRead

func (p *PCM) MmapRead(data any) (int, error)

MmapRead reads interleaved audio data from a capture MMAP PCM device. data must be a slice of a supported numeric type (e.g., []int16, []float32) that will receive the data. It automatically handles waiting for data and starting the stream on the first read.

func (*PCM) MmapWrite

func (p *PCM) MmapWrite(data any) (int, error)

MmapWrite writes interleaved audio data to a playback MMAP PCM device. data must be a slice of a supported numeric type (e.g., []int16, []float32). It automatically handles waiting for buffer space and starting the stream once the 'StartThreshold' is met.

func (*PCM) Pause

func (p *PCM) Pause(enable bool) error

Pause pauses or resumes the PCM stream. Calling Pause(true) on a running stream will pause it. Calling Pause(false) on a paused stream will resume it.

func (*PCM) PeriodCount

func (p *PCM) PeriodCount() uint32

PeriodCount returns the number of periods in the buffer.

func (*PCM) PeriodSize

func (p *PCM) PeriodSize() uint32

PeriodSize returns the number of frames per period.

func (*PCM) PeriodTime

func (p *PCM) PeriodTime() time.Duration

PeriodTime returns the duration of a single period.

func (*PCM) Prepare

func (p *PCM) Prepare() error

Prepare readies the PCM device for I/O operations. This is typically used to recover from an XRUN.

func (*PCM) Rate

func (p *PCM) Rate() uint32

Rate returns the sample rate of the PCM stream in Hz.

func (*PCM) Read

func (p *PCM) Read(data any) error

Read reads audio samples from a PCM device. This function is for compatibility with tinyalsa's deprecated pcm_read. It calculates the number of frames based on the buffer slice size and calls ReadI. data must be a slice of a supported numeric type (e.g., []int16, []float32). Returns nil on success or an error on failure.

func (*PCM) ReadI

func (p *PCM) ReadI(buffer any, frames uint32) (int, error)

ReadI reads interleaved audio data from a capture PCM device using an ioctl call. buffer must be a slice of a supported numeric type (e.g., []int16, []float32). This is the idiomatic way to perform blocking I/O with ALSA. It automatically starts the stream, recovers from overruns (EPIPE), and loops until the buffer is filled with the requested number of frames or an unrecoverable error occurs. Returns the number of frames actually read.

func (*PCM) ReadN

func (p *PCM) ReadN(buffers [][]byte, frames uint32) (int, error)

ReadN reads non-interleaved audio data from a capture PCM device. This function is for non-MMAP, non-interleaved access. The provided `buffers` slice must contain one slice per channel (e.g., `[][]byte`), each large enough to hold 'frames' of audio data. It uses the `SNDRV_PCM_IOCTL_READN_FRAMES` ioctl. Like ReadI, it handles overruns by preparing and retrying the read. Returns the number of frames actually read.

func (*PCM) Resume

func (p *PCM) Resume() error

Resume resumes a suspended PCM stream.

func (*PCM) SetConfig

func (p *PCM) SetConfig(config *Config) error

SetConfig sets the hardware and software parameters for the PCM device. This function should be called before the stream is started. If called on an already configured stream, it will attempt to reconfigure it, which may only succeed if the stream is stopped.

func (*PCM) Start

func (p *PCM) Start() error

Start explicitly starts the PCM stream. It ensures the stream is prepared before starting.

func (*PCM) State

func (p *PCM) State() (PcmState, error)

State returns the current cached state of the PCM stream.

func (*PCM) Stop

func (p *PCM) Stop() error

Stop abruptly stops the PCM stream, dropping any pending frames.

func (*PCM) Subdevice

func (p *PCM) Subdevice() uint32

Subdevice returns the subdevice number of the PCM stream.

func (*PCM) Timestamp

func (p *PCM) Timestamp() (availFrames uint32, t time.Time, err error)

Timestamp returns available frames and the corresponding timestamp. The clock source is CLOCK_MONOTONIC if the PCM_MONOTONIC flag was used, otherwise it is CLOCK_REALTIME. This function is only available for MMAP streams.

func (p *PCM) Unlink() error

Unlink removes the synchronization between this PCM and others.

func (*PCM) Wait

func (p *PCM) Wait(timeoutMs int) (bool, error)

Wait waits for the PCM to become ready for I/O or until a timeout occurs. Returns true if the device is ready, false on timeout. On error, it may return a specific error code like EPIPE, ESTRPIPE, ENODEV, or EIO.

func (*PCM) Write

func (p *PCM) Write(data any) error

Write writes audio samples to a PCM device. This function is for compatibility with tinyalsa's deprecated pcm_write. It calculates the number of frames based on the input slice size and calls WriteI. data must be a slice of a supported numeric type (e.g., []int16, []float32). Returns nil on success or an error on failure.

func (*PCM) WriteI

func (p *PCM) WriteI(data any, frames uint32) (int, error)

WriteI writes interleaved audio data to a playback PCM device using an ioctl call. data must be a slice of a supported numeric type (e.g., []int16, []float32). This is the idiomatic way to perform blocking I/O with ALSA. It automatically prepares and starts the stream, recovers from underruns (EPIPE), and loops until all requested frames have been written or an unrecoverable error occurs. Returns the number of frames actually written.

func (*PCM) WriteN

func (p *PCM) WriteN(data [][]byte, frames uint32) (int, error)

WriteN writes non-interleaved audio data to a playback PCM device. This function is for non-MMAP, non-interleaved access. It is less common than interleaved I/O. The `data` slice should contain one slice per channel (e.g., `[][]byte`), each containing 'frames' worth of sample data. It uses the `SNDRV_PCM_IOCTL_WRITEN_FRAMES` ioctl. Like WriteI, it handles underruns by preparing and retrying the write. Returns the number of frames actually written.

func (*PCM) Xruns

func (p *PCM) Xruns() int

Xruns returns the number of buffer underruns (for playback) or overruns (for capture) that have occurred. An xrun is a serious error that indicates the hardware buffer was not serviced in time, leading to an audible glitch.

type PcmFlag

type PcmFlag uint32

PcmFlag defines flags for opening a PCM stream.

const (
	// PCM_OUT specifies a playback stream.
	PCM_OUT PcmFlag = 0
	// PCM_IN specifies a capture stream.
	PCM_IN PcmFlag = 0x10000000

	// PCM_MMAP specifies that the stream will use memory-mapped I/O.
	PCM_MMAP PcmFlag = 0x00000001
	// PCM_NONBLOCK specifies that I/O operations should not block.
	PCM_NONBLOCK PcmFlag = 0x00000010
	// PCM_NORESTART specifies that the driver should not automatically restart the stream on underrun.
	PCM_NORESTART PcmFlag = 0x00000002
	// PCM_MONOTONIC requests monotonic timestamps instead of wall clock time.
	PCM_MONOTONIC PcmFlag = 0x00000004
	// PCM_NOIRQ specifies that the driver should not generate IRQs for every period.
	// This is an optimization for MMAP streams that can reduce CPU usage.
	// When used, Wait() will use a calculated timeout instead of blocking indefinitely.
	PCM_NOIRQ PcmFlag = 0x00000008
)

type PcmFormat

type PcmFormat int32

PcmFormat defines the sample format for a PCM stream. These values correspond to the SNDRV_PCM_FORMAT_* constants in the ALSA kernel headers.

const (
	PCM_FORMAT_INVALID            PcmFormat = -1
	PCM_FORMAT_S8                 PcmFormat = 0
	PCM_FORMAT_U8                 PcmFormat = 1
	PCM_FORMAT_S16_LE             PcmFormat = 2
	PCM_FORMAT_S16_BE             PcmFormat = 3
	PCM_FORMAT_U16_LE             PcmFormat = 4
	PCM_FORMAT_U16_BE             PcmFormat = 5
	PCM_FORMAT_S24_LE             PcmFormat = 6
	PCM_FORMAT_S24_BE             PcmFormat = 7
	PCM_FORMAT_U24_LE             PcmFormat = 8
	PCM_FORMAT_U24_BE             PcmFormat = 9
	PCM_FORMAT_S32_LE             PcmFormat = 10
	PCM_FORMAT_S32_BE             PcmFormat = 11
	PCM_FORMAT_U32_LE             PcmFormat = 12
	PCM_FORMAT_U32_BE             PcmFormat = 13
	PCM_FORMAT_FLOAT_LE           PcmFormat = 14
	PCM_FORMAT_FLOAT_BE           PcmFormat = 15
	PCM_FORMAT_FLOAT64_LE         PcmFormat = 16
	PCM_FORMAT_FLOAT64_BE         PcmFormat = 17
	PCM_FORMAT_IEC958_SUBFRAME_LE PcmFormat = 18
	PCM_FORMAT_IEC958_SUBFRAME_BE PcmFormat = 19
	PCM_FORMAT_MU_LAW             PcmFormat = 20
	PCM_FORMAT_A_LAW              PcmFormat = 21
	PCM_FORMAT_IMA_ADPCM          PcmFormat = 22
	PCM_FORMAT_MPEG               PcmFormat = 23
	PCM_FORMAT_GSM                PcmFormat = 24
	PCM_FORMAT_SPECIAL            PcmFormat = 31
	PCM_FORMAT_S24_3LE            PcmFormat = 32
	PCM_FORMAT_S24_3BE            PcmFormat = 33
	PCM_FORMAT_U24_3LE            PcmFormat = 34
	PCM_FORMAT_U24_3BE            PcmFormat = 35
	PCM_FORMAT_S20_3LE            PcmFormat = 36
	PCM_FORMAT_S20_3BE            PcmFormat = 37
	PCM_FORMAT_U20_3LE            PcmFormat = 38
	PCM_FORMAT_U20_3BE            PcmFormat = 39
	PCM_FORMAT_S18_3LE            PcmFormat = 40
	PCM_FORMAT_S18_3BE            PcmFormat = 41
	PCM_FORMAT_U18_3LE            PcmFormat = 42
	PCM_FORMAT_U18_3BE            PcmFormat = 43
)

type PcmParam

type PcmParam int

PcmParam identifies a hardware parameter for a PCM device. These values correspond to the SNDRV_PCM_HW_PARAM_* constants.

const (
	PCM_PARAM_ACCESS       PcmParam = 0
	PCM_PARAM_FORMAT       PcmParam = 1
	PCM_PARAM_SUBFORMAT    PcmParam = 2
	PCM_PARAM_SAMPLE_BITS  PcmParam = 8
	PCM_PARAM_FRAME_BITS   PcmParam = 9
	PCM_PARAM_CHANNELS     PcmParam = 10
	PCM_PARAM_RATE         PcmParam = 11
	PCM_PARAM_PERIOD_TIME  PcmParam = 12
	PCM_PARAM_PERIOD_SIZE  PcmParam = 13
	PCM_PARAM_PERIOD_BYTES PcmParam = 14
	PCM_PARAM_PERIODS      PcmParam = 15
	PCM_PARAM_BUFFER_TIME  PcmParam = 16
	PCM_PARAM_BUFFER_SIZE  PcmParam = 17
	PCM_PARAM_BUFFER_BYTES PcmParam = 18
	PCM_PARAM_TICK_TIME    PcmParam = 19
)

type PcmParamMask

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

PcmParamMask represents a bitmask for a PCM hardware parameter. It allows checking which specific capabilities (e.g., formats) are supported.

func (*PcmParamMask) Test

func (m *PcmParamMask) Test(bit uint) bool

Test checks if a specific bit in the mask is set.

type PcmParams

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

PcmParams represents the hardware capabilities of a PCM device.

func PcmParamsGet

func PcmParamsGet(card, device uint, flags PcmFlag) (*PcmParams, error)

PcmParamsGet queries the hardware parameters for a given PCM device without fully opening it. This is useful for discovering device capabilities.

func (*PcmParams) FormatIsSupported

func (pp *PcmParams) FormatIsSupported(format PcmFormat) bool

FormatIsSupported checks if a given PCM format is supported.

func (*PcmParams) Free

func (pp *PcmParams) Free()

Free releases the resources associated with PcmParams.

func (*PcmParams) Mask

func (pp *PcmParams) Mask(param PcmParam) (*PcmParamMask, error)

Mask returns the bitmask for a mask-type parameter.

func (*PcmParams) RangeMax

func (pp *PcmParams) RangeMax(param PcmParam) (uint32, error)

RangeMax returns the maximum value for an interval parameter.

func (*PcmParams) RangeMin

func (pp *PcmParams) RangeMin(param PcmParam) (uint32, error)

RangeMin returns the minimum value for an interval parameter.

func (*PcmParams) String

func (pp *PcmParams) String() string

String returns a human-readable representation of the PCM device's capabilities.

type PcmState

type PcmState int32

PcmState defines the current state of a PCM stream. These values correspond to the SNDRV_PCM_STATE_* constants.

const (
	PCM_STATE_OPEN         PcmState = 0 // Stream is open.
	PCM_STATE_SETUP        PcmState = 1 // Stream has a setup.
	PCM_STATE_PREPARED     PcmState = 2 // Stream is ready to start.
	PCM_STATE_RUNNING      PcmState = 3 // Stream is running.
	PCM_STATE_XRUN         PcmState = 4 // Stream reached an underrun or overrun.
	PCM_STATE_DRAINING     PcmState = 5 // Stream is draining.
	PCM_STATE_PAUSED       PcmState = 6 // Stream is paused.
	PCM_STATE_SUSPENDED    PcmState = 7 // Hardware is suspended.
	PCM_STATE_DISCONNECTED PcmState = 8 // Hardware is disconnected.
)

type SndAesEbu

type SndAesEbu struct {
	Status      [24]byte
	Subcode     [147]byte
	Pad         byte
	DigSubframe [4]byte
}

SndAesEbu is the Go representation of the C struct for IEC958 (S/PDIF) data. It is part of the sndCtlElemValue union.

type SndPcmSframesT added in v0.2.1

type SndPcmSframesT = int64

SndPcmSframesT is a signed long in the ALSA headers. On 64-bit architectures, this is a 64-bit signed integer.

type SndPcmUframesT

type SndPcmUframesT = uint64

SndPcmUframesT is an unsigned long in the ALSA headers. On 64-bit architectures, this is a 64-bit unsigned integer.

Directories

Path Synopsis
cmd
cap command
mix command
pcminfo command
play command

Jump to

Keyboard shortcuts

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