alsa

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2025 License: BSD-3-Clause Imports: 15 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 and tests for usage examples.

Notes

This library does not support the ALSA plugin architecture and will only open direct hardware devices.

No dmix plugin that enables multiple applications to share a single audio output device. Additionally, no speex plugin that typically handles automatic conversions for sample rate and format (e.g., S16_LE to S32_LE).

The user is responsible for making sure that the provided audio data matches the exact hardware capabilities of the PCM device. These capabilities can be queried using the PcmParamsGet function.

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

You can load them with the following commands:

sudo modprobe snd-aloop
sudo modprobe snd-dummy

Documentation

Overview

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

It offers low-level, direct access to sound hardware devices without relying on the alsa-lib library. This package communicates with the ALSA kernel drivers primarily through ioctl syscalls.

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 sndInterval.Flags.

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_HWSYNC    = 1 << 0
	SNDRV_PCM_SYNC_PTR_APPL      = 1 << 1
	SNDRV_PCM_SYNC_PTR_AVAIL_MIN = 1 << 2
)
View Source
const (
	SNDRV_PCM_ACCESS_MMAP_INTERLEAVED = 0
	SNDRV_PCM_ACCESS_RW_INTERLEAVED   = 3
)

Variables

View Source
var (
	// PCM IOCTLs
	SNDRV_PCM_IOCTL_HW_REFINE     uintptr
	SNDRV_PCM_IOCTL_HW_PARAMS     uintptr
	SNDRV_PCM_IOCTL_HW_FREE       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{
	SNDRV_PCM_FORMAT_S8:                 "S8",
	SNDRV_PCM_FORMAT_U8:                 "U8",
	SNDRV_PCM_FORMAT_S16_LE:             "S16_LE",
	SNDRV_PCM_FORMAT_S16_BE:             "S16_BE",
	SNDRV_PCM_FORMAT_U16_LE:             "U16_LE",
	SNDRV_PCM_FORMAT_U16_BE:             "U16_BE",
	SNDRV_PCM_FORMAT_S24_LE:             "S24_LE",
	SNDRV_PCM_FORMAT_S24_BE:             "S24_BE",
	SNDRV_PCM_FORMAT_U24_LE:             "U24_LE",
	SNDRV_PCM_FORMAT_U24_BE:             "U24_BE",
	SNDRV_PCM_FORMAT_S32_LE:             "S32_LE",
	SNDRV_PCM_FORMAT_S32_BE:             "S32_BE",
	SNDRV_PCM_FORMAT_U32_LE:             "U32_LE",
	SNDRV_PCM_FORMAT_U32_BE:             "U32_BE",
	SNDRV_PCM_FORMAT_FLOAT_LE:           "FLOAT_LE",
	SNDRV_PCM_FORMAT_FLOAT_BE:           "FLOAT_BE",
	SNDRV_PCM_FORMAT_FLOAT64_LE:         "FLOAT64_LE",
	SNDRV_PCM_FORMAT_FLOAT64_BE:         "FLOAT64_BE",
	SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE: "IEC958_SUBFRAME_LE",
	SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE: "IEC958_SUBFRAME_BE",
	SNDRV_PCM_FORMAT_MU_LAW:             "MU_LAW",
	SNDRV_PCM_FORMAT_A_LAW:              "A_LAW",
	SNDRV_PCM_FORMAT_IMA_ADPCM:          "IMA_ADPCM",
	SNDRV_PCM_FORMAT_MPEG:               "MPEG",
	SNDRV_PCM_FORMAT_GSM:                "GSM",
	SNDRV_PCM_FORMAT_SPECIAL:            "SPECIAL",
	SNDRV_PCM_FORMAT_S24_3LE:            "S24_3LE",
	SNDRV_PCM_FORMAT_S24_3BE:            "S24_3BE",
	SNDRV_PCM_FORMAT_U24_3LE:            "U24_3LE",
	SNDRV_PCM_FORMAT_U24_3BE:            "U24_3BE",
	SNDRV_PCM_FORMAT_S20_3LE:            "S20_3LE",
	SNDRV_PCM_FORMAT_S20_3BE:            "S20_3BE",
	SNDRV_PCM_FORMAT_U20_3LE:            "U20_3LE",
	SNDRV_PCM_FORMAT_U20_3BE:            "U20_3BE",
	SNDRV_PCM_FORMAT_S18_3LE:            "S18_3LE",
	SNDRV_PCM_FORMAT_S18_3BE:            "S18_3BE",
	SNDRV_PCM_FORMAT_U18_3LE:            "U18_3LE",
	SNDRV_PCM_FORMAT_U18_3BE:            "U18_3BE",
	SNDRV_PCM_FORMAT_DSD_U8:             "DSD_U8",
	SNDRV_PCM_FORMAT_DSD_U16_LE:         "DSD_U16_LE",
	SNDRV_PCM_FORMAT_DSD_U16_BE:         "DSD_U16_BE",
	SNDRV_PCM_FORMAT_DSD_U32_LE:         "DSD_U32_LE",
	SNDRV_PCM_FORMAT_DSD_U32_BE:         "DSD_U32_BE",
}

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

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

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 uint32
	SilenceSize      uint32
	AvailMin         uint32
}

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

type HwParamsFlag added in v0.4.0

type HwParamsFlag uint32

HwParamsFlag defines flags for the snd_pcm_hw_params structure.

const (
	// SNDRV_PCM_HW_PARAMS_NO_RESAMPLE - if set, disables automatic rate resampling by the driver.
	SNDRV_PCM_HW_PARAMS_NO_RESAMPLE HwParamsFlag = 1 << 0
	// SNDRV_PCM_HW_PARAMS_EXPORT_BUFFER - if set, allows the application to export the DMA buffer.
	SNDRV_PCM_HW_PARAMS_EXPORT_BUFFER HwParamsFlag = 1 << 1
	// SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP - if set, disables period wakeups, reducing CPU usage. Used with PCM_NOIRQ.
	SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP HwParamsFlag = 1 << 2
)

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.

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:

  • SNDRV_CTL_ELEM_TYPE_BOOLEAN, _INT, _ENUM: *[]int32
  • SNDRV_CTL_ELEM_TYPE_BYTES: *[]byte
  • SNDRV_CTL_ELEM_TYPE_INTEGER64: *[]int64
  • SNDRV_CTL_ELEM_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:

  • SNDRV_CTL_ELEM_TYPE_BOOLEAN, _INT, _ENUM: []int32
  • SNDRV_CTL_ELEM_TYPE_BYTES: []byte
  • SNDRV_CTL_ELEM_TYPE_INTEGER64: []int64
  • SNDRV_CTL_ELEM_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 MixerCtlAccessFlag added in v0.4.0

type MixerCtlAccessFlag uint32

MixerCtlAccessFlag defines the access permissions for a mixer control.

const (
	// SNDRV_CTL_ELEM_ACCESS_READ - if set, the control is readable.
	SNDRV_CTL_ELEM_ACCESS_READ MixerCtlAccessFlag = 1 << 0
	// SNDRV_CTL_ELEM_ACCESS_WRITE - if set, the control is writable.
	SNDRV_CTL_ELEM_ACCESS_WRITE MixerCtlAccessFlag = 1 << 1
	// SNDRV_CTL_ELEM_ACCESS_TLV_READ indicates that TLV read is possible for the control.
	SNDRV_CTL_ELEM_ACCESS_TLV_READ MixerCtlAccessFlag = 1 << 12
	// SNDRV_CTL_ELEM_ACCESS_TLV_WRITE indicates that TLV write is possible for the control.
	SNDRV_CTL_ELEM_ACCESS_TLV_WRITE MixerCtlAccessFlag = 1 << 13
)

type MixerCtlType

type MixerCtlType int32

MixerCtlType defines the value type of mixer control.

const (
	SNDRV_CTL_ELEM_TYPE_BOOLEAN    MixerCtlType = 1
	SNDRV_CTL_ELEM_TYPE_INTEGER    MixerCtlType = 2
	SNDRV_CTL_ELEM_TYPE_ENUMERATED MixerCtlType = 3
	SNDRV_CTL_ELEM_TYPE_BYTES      MixerCtlType = 4
	SNDRV_CTL_ELEM_TYPE_IEC958     MixerCtlType = 5
	SNDRV_CTL_ELEM_TYPE_INTEGER64  MixerCtlType = 6
	SNDRV_CTL_ELEM_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

	// SNDRV_CTL_EVENT_MASK_VALUE indicates that a control element's value has changed.
	SNDRV_CTL_EVENT_MASK_VALUE MixerEventType = 1 << 0
	// SNDRV_CTL_EVENT_MASK_INFO indicates that a control element's metadata (e.g., range) has changed.
	SNDRV_CTL_EVENT_MASK_INFO MixerEventType = 1 << 1
	// SNDRV_CTL_EVENT_MASK_ADD indicates that a control element has been added.
	SNDRV_CTL_EVENT_MASK_ADD MixerEventType = 1 << 2
	// SNDRV_CTL_EVENT_MASK_REMOVE 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) 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.

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

func (p *PCM) IsReady() bool

IsReady checks if the PCM handle is valid.

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

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

MmapRead reads interleaved audio data from a capture MMAP PCM device. The provided `data` must be a slice of a supported numeric type (e.g., []int16, []float32) that will receive the data. Returns the number of frames actually read.

func (*PCM) MmapWrite

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

MmapWrite writes interleaved audio data to a playback MMAP PCM device. The provided `data` must be a slice of a supported numeric type (e.g., []int16, []float32). Returns the number of frames actually written.

func (*PCM) Pause

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

Pause pauses or resumes the PCM stream.

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) (int, error)

Read reads interleaved audio data from a capture PCM device using an ioctl call. The provided `buffer` must be a slice of a supported numeric type (e.g., []int16, []float32). Returns the number of frames actually read.

func (*PCM) Resume

func (p *PCM) Resume() error

Resume resumes a suspended PCM stream (system suspend, when state is SND_PCM_STATE_SUSPENDED).

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.

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

State returns the current 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.

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.

func (*PCM) Write

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

Write writes interleaved audio data to a playback PCM device using an ioctl call. The provided `data` argument must be a slice of a supported numeric type (e.g., []int16, []float32). 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.

type PcmAccess added in v0.2.3

type PcmAccess int32

PcmAccess defines the type of PCM access.

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.

const (
	SNDRV_PCM_FORMAT_INVALID            PcmFormat = -1
	SNDRV_PCM_FORMAT_S8                 PcmFormat = 0
	SNDRV_PCM_FORMAT_U8                 PcmFormat = 1
	SNDRV_PCM_FORMAT_S16_LE             PcmFormat = 2
	SNDRV_PCM_FORMAT_S16_BE             PcmFormat = 3
	SNDRV_PCM_FORMAT_U16_LE             PcmFormat = 4
	SNDRV_PCM_FORMAT_U16_BE             PcmFormat = 5
	SNDRV_PCM_FORMAT_S24_LE             PcmFormat = 6
	SNDRV_PCM_FORMAT_S24_BE             PcmFormat = 7
	SNDRV_PCM_FORMAT_U24_LE             PcmFormat = 8
	SNDRV_PCM_FORMAT_U24_BE             PcmFormat = 9
	SNDRV_PCM_FORMAT_S32_LE             PcmFormat = 10
	SNDRV_PCM_FORMAT_S32_BE             PcmFormat = 11
	SNDRV_PCM_FORMAT_U32_LE             PcmFormat = 12
	SNDRV_PCM_FORMAT_U32_BE             PcmFormat = 13
	SNDRV_PCM_FORMAT_FLOAT_LE           PcmFormat = 14
	SNDRV_PCM_FORMAT_FLOAT_BE           PcmFormat = 15
	SNDRV_PCM_FORMAT_FLOAT64_LE         PcmFormat = 16
	SNDRV_PCM_FORMAT_FLOAT64_BE         PcmFormat = 17
	SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE PcmFormat = 18
	SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE PcmFormat = 19
	SNDRV_PCM_FORMAT_MU_LAW             PcmFormat = 20
	SNDRV_PCM_FORMAT_A_LAW              PcmFormat = 21
	SNDRV_PCM_FORMAT_IMA_ADPCM          PcmFormat = 22
	SNDRV_PCM_FORMAT_MPEG               PcmFormat = 23
	SNDRV_PCM_FORMAT_GSM                PcmFormat = 24
	SNDRV_PCM_FORMAT_SPECIAL            PcmFormat = 31
	SNDRV_PCM_FORMAT_S24_3LE            PcmFormat = 32
	SNDRV_PCM_FORMAT_S24_3BE            PcmFormat = 33
	SNDRV_PCM_FORMAT_U24_3LE            PcmFormat = 34
	SNDRV_PCM_FORMAT_U24_3BE            PcmFormat = 35
	SNDRV_PCM_FORMAT_S20_3LE            PcmFormat = 36
	SNDRV_PCM_FORMAT_S20_3BE            PcmFormat = 37
	SNDRV_PCM_FORMAT_U20_3LE            PcmFormat = 38
	SNDRV_PCM_FORMAT_U20_3BE            PcmFormat = 39
	SNDRV_PCM_FORMAT_S18_3LE            PcmFormat = 40
	SNDRV_PCM_FORMAT_S18_3BE            PcmFormat = 41
	SNDRV_PCM_FORMAT_U18_3LE            PcmFormat = 42
	SNDRV_PCM_FORMAT_U18_3BE            PcmFormat = 43
	SNDRV_PCM_FORMAT_DSD_U8             PcmFormat = 44
	SNDRV_PCM_FORMAT_DSD_U16_LE         PcmFormat = 45
	SNDRV_PCM_FORMAT_DSD_U16_BE         PcmFormat = 46
	SNDRV_PCM_FORMAT_DSD_U32_LE         PcmFormat = 47
	SNDRV_PCM_FORMAT_DSD_U32_BE         PcmFormat = 48
)

type PcmParam

type PcmParam int

PcmParam identifies a hardware parameter for a PCM device.

const (
	// SNDRV_PCM_HW_PARAM_ACCESS is the access type (e.g., RW_INTERLEAVED, MMAP_INTERLEAVED).
	SNDRV_PCM_HW_PARAM_ACCESS PcmParam = 0
	// SNDRV_PCM_HW_PARAM_FORMAT is the sample format (e.g., S16_LE).
	SNDRV_PCM_HW_PARAM_FORMAT PcmParam = 1
	// SNDRV_PCM_HW_PARAM_SUBFORMAT is the sample subformat (e.g., STD).
	SNDRV_PCM_HW_PARAM_SUBFORMAT PcmParam = 2
	// SNDRV_PCM_HW_PARAM_SAMPLE_BITS is the number of bits per sample.
	SNDRV_PCM_HW_PARAM_SAMPLE_BITS PcmParam = 8
	// SNDRV_PCM_HW_PARAM_FRAME_BITS is the number of bits per frame (sample_bits * channels).
	SNDRV_PCM_HW_PARAM_FRAME_BITS PcmParam = 9
	// SNDRV_PCM_HW_PARAM_CHANNELS is the number of audio channels.
	SNDRV_PCM_HW_PARAM_CHANNELS PcmParam = 10
	// SNDRV_PCM_HW_PARAM_RATE is the sample rate in Hz.
	SNDRV_PCM_HW_PARAM_RATE PcmParam = 11
	// SNDRV_PCM_HW_PARAM_PERIOD_TIME is the duration of one period in microseconds.
	SNDRV_PCM_HW_PARAM_PERIOD_TIME PcmParam = 12
	// SNDRV_PCM_HW_PARAM_PERIOD_SIZE is the size of one period in frames.
	SNDRV_PCM_HW_PARAM_PERIOD_SIZE PcmParam = 13
	// SNDRV_PCM_HW_PARAM_PERIOD_BYTES is the size of one period in bytes.
	SNDRV_PCM_HW_PARAM_PERIOD_BYTES PcmParam = 14
	// SNDRV_PCM_HW_PARAM_PERIODS is the total number of periods in the buffer.
	SNDRV_PCM_HW_PARAM_PERIODS PcmParam = 15
	// SNDRV_PCM_HW_PARAM_BUFFER_TIME is the total buffer duration in microseconds.
	SNDRV_PCM_HW_PARAM_BUFFER_TIME PcmParam = 16
	// SNDRV_PCM_HW_PARAM_BUFFER_SIZE is the total buffer size in frames.
	SNDRV_PCM_HW_PARAM_BUFFER_SIZE PcmParam = 17
	// SNDRV_PCM_HW_PARAM_BUFFER_BYTES is the total buffer size in bytes.
	SNDRV_PCM_HW_PARAM_BUFFER_BYTES PcmParam = 18
	// SNDRV_PCM_HW_PARAM_TICK_TIME is the duration of one tick in microseconds.
	SNDRV_PCM_HW_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 to get its default settings. This function initializes the parameters and then uses the SNDRV_PCM_IOCTL_HW_PARAMS ioctl. The kernel then fills the structure with the hardware's default or current settings.

func (*PcmParams) FormatIsSupported

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

FormatIsSupported checks if a given PCM format is supported.

func (*PcmParams) Mask

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

Mask returns the bitmask for a mask-type parameter.

func (*PcmParams) Max added in v0.5.0

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

Max returns the maximum value for an interval parameter.

func (*PcmParams) Min added in v0.5.0

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

Min 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.

const (
	// SNDRV_PCM_STATE_OPEN indicates the stream is open but not yet configured.
	SNDRV_PCM_STATE_OPEN PcmState = 0
	// SNDRV_PCM_STATE_SETUP indicates the stream has been configured but not prepared.
	SNDRV_PCM_STATE_SETUP PcmState = 1
	// SNDRV_PCM_STATE_PREPARED indicates the stream is prepared and ready for I/O.
	SNDRV_PCM_STATE_PREPARED PcmState = 2
	// SNDRV_PCM_STATE_RUNNING indicates the stream is actively transferring data.
	SNDRV_PCM_STATE_RUNNING PcmState = 3
	// SNDRV_PCM_STATE_XRUN indicates an underrun (for playback) or overrun (for capture) occurred.
	SNDRV_PCM_STATE_XRUN PcmState = 4
	// SNDRV_PCM_STATE_DRAINING indicates the stream is playing out the last remaining frames in the buffer.
	SNDRV_PCM_STATE_DRAINING PcmState = 5
	// SNDRV_PCM_STATE_PAUSED indicates the stream is paused.
	SNDRV_PCM_STATE_PAUSED PcmState = 6
	// SNDRV_PCM_STATE_SUSPENDED indicates the hardware is in a suspended state (e.g., due to power management).
	SNDRV_PCM_STATE_SUSPENDED PcmState = 7
	// SNDRV_PCM_STATE_DISCONNECTED indicates the hardware has been disconnected.
	SNDRV_PCM_STATE_DISCONNECTED PcmState = 8
)

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 SoundCard added in v0.4.1

type SoundCard struct {
	ID          int
	Name        string
	Description string
	Devices     []SoundCardDevice
}

SoundCard represents an enumerated sound card with its devices.

func EnumerateCards added in v0.4.1

func EnumerateCards() ([]SoundCard, error)

EnumerateCards scans /proc/asound to find all available sound cards and their PCM devices.

func (SoundCard) String added in v0.4.1

func (c SoundCard) String() string

String returns a human-readable representation of the SoundCard.

type SoundCardDevice added in v0.4.1

type SoundCardDevice struct {
	ID          int
	Name        string
	Description string
	IsPlayback  bool // True for playback, false for capture
}

SoundCardDevice represents a single PCM device on a sound card.

func (SoundCardDevice) String added in v0.4.1

func (d SoundCardDevice) String() string

String returns a human-readable representation of the SoundCardDevice.

Jump to

Keyboard shortcuts

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