package module
Version: v0.10.35 Latest Latest

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

Go to latest
Published: May 7, 2021 License: Unlicense Imports: 6 Imported by: 38



TravisCI Build Status AppVeyor Build Status GoDoc Go Report Card

Go bindings for miniaudio library.

Requires cgo but does not require linking to anything on the Windows/macOS and it links only -ldl on Linux/BSDs.


go get -u


Documentation on GoDoc. Also check examples.


  • Windows (WASAPI, DirectSound, WinMM)
  • Linux (PulseAudio, ALSA, JACK)
  • FreeBSD/NetBSD/OpenBSD (OSS/audio(4)/sndio)
  • macOS (CoreAudio)
  • Android (OpenSL|ES, AAudio)



Package malgo - Mini audio library (miniaudio cgo bindings).



View Source
const (
	BackendWasapi = iota

Backend enumeration.

View Source
const (
	Success = 0

	//  General errors.
	Error            = -1 // a generic error
	InvalidArgs      = -2
	InvalidPperation = -3
	OutOfMemory      = -4
	AccessDenied     = -5
	TooLarge         = -6
	Timeout          = -7

	// General miniaudio-specific errors.
	FormatNotSupported     = -100
	DeviceTypeNotSupported = -101
	ShareModeNotSupported  = -102
	NoBackend              = -103
	NoDevice               = -104
	APINotFound            = -105
	InvalidDeviceConfig    = -106

	// State errors.
	DeviceBusy           = -200
	DeviceNotInitialized = -201
	DeviceNotStarted     = -202
	DeviceUnavailable    = -203

	// Operation errors.
	FailedToMapDeviceBuffer        = -300
	FailedToUnmapDeviceBuffer      = -301
	FailedToInitBackend            = -302
	FailedToReadDataFromDevice     = -304
	FailedToReadDataFromClient     = -303
	FailedToSendDataToClient       = -305
	FailedToSendDataToDevice       = -306
	FailedToOpenBackendDevice      = -307
	FailedToStartBackendDevice     = -308
	FailedToStopBackendDevice      = -309
	FailedToConfigureBackendDevice = -310
	FailedToCreateMutex            = -311
	FailedToCreateEvent            = -312
	FailedToCreateThread           = -313

Return codes.

View Source
const (
	IOSSessionCategoryOptionMixWithOthers                        = 0x01 // AVAudioSessionCategoryOptionMixWithOthers
	IOSSessionCategoryOptionDuckOthers                           = 0x02 // AVAudioSessionCategoryOptionDuckOthers
	IOSSessionCategoryOptionAllowBluetooth                       = 0x04 // AVAudioSessionCategoryOptionAllowBluetooth
	IOSSessionCategoryOptionDefaultToSpeaker                     = 0x08 // AVAudioSessionCategoryOptionDefaultToSpeaker
	IOSSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers = 0x11 // AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers
	IOSSessionCategoryOptionAllowBluetoothA2dp                   = 0x20 // AVAudioSessionCategoryOptionAllowBluetoothA2DP
	IOSSessionCategoryOptionAllowAirPlay                         = 0x40 // AVAudioSessionCategoryOptionAllowAirPlay

IOSSessionCategoryOptions enumeration.


View Source
var (
	ErrError                          = fmt.Errorf("%s: generic error", errTag)
	ErrInvalidArgs                    = fmt.Errorf("%s: invalid args", errTag)
	ErrInvalidPperation               = fmt.Errorf("%s: invalid pperation", errTag)
	ErrOutOfMemory                    = fmt.Errorf("%s: out o fmemory", errTag)
	ErrAccessDenied                   = fmt.Errorf("%s: access denied", errTag)
	ErrTooLarge                       = fmt.Errorf("%s: too large", errTag)
	ErrTimeout                        = fmt.Errorf("%s: timeout", errTag)
	ErrFormatNotSupported             = fmt.Errorf("%s: format not supported", errTag)
	ErrDeviceTypeNotSupported         = fmt.Errorf("%s: device type not supported", errTag)
	ErrShareModeNotSupported          = fmt.Errorf("%s: share mode not supported", errTag)
	ErrNoBackend                      = fmt.Errorf("%s: no backend", errTag)
	ErrNoDevice                       = fmt.Errorf("%s: no device", errTag)
	ErrAPINotFound                    = fmt.Errorf("%s: api not found", errTag)
	ErrInvalidDeviceConfig            = fmt.Errorf("%s: invalid device config", errTag)
	ErrDeviceBusy                     = fmt.Errorf("%s: device busy", errTag)
	ErrDeviceNotInitialized           = fmt.Errorf("%s: device not initialized", errTag)
	ErrDeviceNotStarted               = fmt.Errorf("%s: device not started", errTag)
	ErrDeviceUnavailable              = fmt.Errorf("%s: device unavailable", errTag)
	ErrFailedToMapDeviceBuffer        = fmt.Errorf("%s: failed to map device buffer", errTag)
	ErrFailedToUnmapDeviceBuffer      = fmt.Errorf("%s: failed to unmap device buffer", errTag)
	ErrFailedToInitBackend            = fmt.Errorf("%s: failed to init backend", errTag)
	ErrFailedToReadDataFromDevice     = fmt.Errorf("%s: failed to read data from device", errTag)
	ErrFailedToReadDataFromClient     = fmt.Errorf("%s: failed to read data from client", errTag)
	ErrFailedToSendDataToClient       = fmt.Errorf("%s: failed to send data to client", errTag)
	ErrFailedToSendDataToDevice       = fmt.Errorf("%s: failed to send data to device", errTag)
	ErrFailedToOpenBackendDevice      = fmt.Errorf("%s: failed to open backend device", errTag)
	ErrFailedToStartBackendDevice     = fmt.Errorf("%s: failed to start backend device", errTag)
	ErrFailedToStopBackendDevice      = fmt.Errorf("%s: failed to stop backend device", errTag)
	ErrFailedToConfigureBackendDevice = fmt.Errorf("%s: failed to configure backend device", errTag)
	ErrFailedToCreateMutex            = fmt.Errorf("%s: failed to create mutex", errTag)
	ErrFailedToCreateEvent            = fmt.Errorf("%s: failed to create event", errTag)
	ErrFailedToCreateThread           = fmt.Errorf("%s: failed to create thread", errTag)



func SampleSizeInBytes

func SampleSizeInBytes(format FormatType) int

SampleSizeInBytes retrieves the size of a sample in bytes for the given format.


type AllocatedContext

type AllocatedContext struct {

AllocatedContext is a Context that has been created by the application. It must be freed after use in order to release resources.

func InitContext

func InitContext(backends []Backend, config ContextConfig, logProc LogProc) (*AllocatedContext, error)

InitContext creates and initializes a context. When the application no longer needs the context instance, it needs to call Free() .

func (*AllocatedContext) Free

func (ctx *AllocatedContext) Free()

Free must be called when the allocated data is no longer used. This function must only be called for an uninitialized context.

type AllocationCallbacks

type AllocationCallbacks struct {
	PUserData *byte
	OnMalloc  *[0]byte
	OnRealloc *[0]byte
	OnFree    *[0]byte

AllocationCallbacks types.

type AlsaContextConfig

type AlsaContextConfig struct {
	UseVerboseDeviceEnumeration uint32

AlsaContextConfig type.

type AlsaDeviceConfig

type AlsaDeviceConfig struct {
	NoMMap         uint32
	NoAutoFormat   uint32
	NoAutoChannles uint32
	NoAutoResample uint32

AlsaDeviceConfig type.

type Backend

type Backend uint32

Backend type.

type Context

type Context uintptr

Context is used for selecting and initializing the relevant backends.

const DefaultContext Context = 0

DefaultContext is an unspecified context. It can be used to initialize a streaming function with implicit context defaults.

func (Context) DeviceInfo added in v0.10.25

func (ctx Context) DeviceInfo(kind DeviceType, id DeviceID, mode ShareMode) (DeviceInfo, error)

DeviceInfo retrieves information about a device of the given type, with the specified ID and share mode.

func (Context) Devices

func (ctx Context) Devices(kind DeviceType) ([]DeviceInfo, error)

Devices retrieves basic information about every active playback or capture device.

func (Context) SetLogProc

func (ctx Context) SetLogProc(proc LogProc)

SetLogProc sets the logging callback for the context.

func (Context) Uninit

func (ctx Context) Uninit() error

Uninit uninitializes a context. Results are undefined if you call this while any device created by this context is still active.

type ContextConfig

type ContextConfig struct {
	LogCallback         *[0]byte
	ThreadPriority      ThreadPriority
	PUserData           *byte
	AllocationCallbacks AllocationCallbacks
	Alsa                AlsaContextConfig
	Pulse               PulseContextConfig
	CoreAudio           CoreAudioConfig
	Jack                JackContextConfig

ContextConfig type.

type CoreAudioConfig

type CoreAudioConfig struct {
	SessionCategory        IOSSessionCategory
	SessionCategoryOptions IOSSessionCategoryOptions

CoreAudioConfig type.

type DataProc

type DataProc func(pOutputSample, pInputSamples []byte, framecount uint32)

DataProc type.

type Device

type Device uintptr

Device represents a streaming instance.

func InitDevice

func InitDevice(context Context, deviceConfig DeviceConfig, deviceCallbacks DeviceCallbacks) (*Device, error)

InitDevice initializes a device.

The device ID can be nil, in which case the default device is used. Otherwise, you can retrieve the ID by calling Context.Devices() and use the ID from the returned data.

Set device ID to nil to use the default device. Do _not_ rely on the first device ID returned by Context.Devices() to be the default device.

The returned instance has to be cleaned up using Uninit().

func (*Device) CaptureChannels

func (dev *Device) CaptureChannels() uint32

CaptureChannels returns number of playback channels.

func (*Device) CaptureFormat

func (dev *Device) CaptureFormat() FormatType

CaptureFormat returns device capture format.

func (*Device) IsStarted

func (dev *Device) IsStarted() bool

IsStarted determines whether or not the device is started.

func (*Device) PlaybackChannels

func (dev *Device) PlaybackChannels() uint32

PlaybackChannels returns number of playback channels.

func (*Device) PlaybackFormat

func (dev *Device) PlaybackFormat() FormatType

PlaybackFormat returns device playback format.

func (*Device) SampleRate

func (dev *Device) SampleRate() uint32

SampleRate returns sample rate.

func (*Device) Start

func (dev *Device) Start() error

Start activates the device. For playback devices this begins playback. For capture devices it begins recording.

For a playback device, this will retrieve an initial chunk of audio data from the client before returning. The reason for this is to ensure there is valid audio data in the buffer, which needs to be done _before_ the device begins playback.

This API waits until the backend device has been started for real by the worker thread. It also waits on a mutex for thread-safety.

func (*Device) Stop

func (dev *Device) Stop() error

Stop puts the device to sleep, but does not uninitialize it. Use Start() to start it up again.

This API needs to wait on the worker thread to stop the backend device properly before returning. It also waits on a mutex for thread-safety. In addition, some backends need to wait for the device to finish playback/recording of the current fragment which can take some time (usually proportionate to the buffer size that was specified at initialization time).

func (*Device) Type

func (dev *Device) Type() DeviceType

Type returns device type.

func (*Device) Uninit

func (dev *Device) Uninit()

Uninit uninitializes a device.

This will explicitly stop the device. You do not need to call Stop() beforehand, but it's harmless if you do.

type DeviceCallbacks

type DeviceCallbacks struct {
	// Data is called for the full duplex IO.
	Data DataProc
	// Stop is called when the device stopped.
	Stop StopProc

DeviceCallbacks contains callbacks for one initialized device.

type DeviceConfig

type DeviceConfig struct {
	DeviceType               DeviceType
	SampleRate               uint32
	PeriodSizeInFrames       uint32
	PeriodSizeInMilliseconds uint32
	Periods                  uint32
	PerformanceProfile       PerformanceProfile
	NoPreZeroedOutputBuffer  uint32
	NoClip                   uint32
	DataCallback             *[0]byte
	StopCallback             *[0]byte
	PUserData                *byte
	Resampling               ResampleConfig
	Playback                 SubConfig
	Capture                  SubConfig
	Wasapi                   WasapiDeviceConfig
	Alsa                     AlsaDeviceConfig
	Pulse                    PulseDeviceConfig

DeviceConfig type.

func DefaultDeviceConfig

func DefaultDeviceConfig(deviceType DeviceType) DeviceConfig

DefaultDeviceConfig returns a default device config.

type DeviceID

type DeviceID [C.sizeof_ma_device_id]byte

DeviceID type.

func (*DeviceID) Pointer added in v0.10.19

func (d *DeviceID) Pointer() unsafe.Pointer

func (DeviceID) String

func (d DeviceID) String() string

String returns the string representation of the identifier. It is the hexadecimal form of the underlying bytes of a minimum length of 2 digits, with trailing zeroes removed.

type DeviceInfo

type DeviceInfo struct {
	ID DeviceID

	IsDefault     uint32
	FormatCount   uint32
	Formats       [6]uint32
	MinChannels   uint32
	MaxChannels   uint32
	MinSampleRate uint32
	MaxSampleRate uint32
	// contains filtered or unexported fields

DeviceInfo type.

func (*DeviceInfo) Name

func (d *DeviceInfo) Name() string

Name returns the name of the device.

func (*DeviceInfo) String

func (d *DeviceInfo) String() string

String returns string.

type DeviceType

type DeviceType uint32

DeviceType type.

const (
	Playback DeviceType = iota + 1

DeviceType enumeration.

type FormatType

type FormatType uint32

FormatType type.

const (
	FormatUnknown FormatType = iota

Format enumeration.

type IOSSessionCategory

type IOSSessionCategory uint32

IOSSessionCategory type.

const (
	IOSSessionCategoryDefault       IOSSessionCategory = iota // AVAudioSessionCategoryPlayAndRecord with AVAudioSessionCategoryOptionDefaultToSpeaker.
	IOSSessionCategoryNone                                    // Leave the session category unchanged.
	IOSSessionCategoryAmbient                                 // AVAudioSessionCategoryAmbient
	IOSSessionCategorySoloAmbient                             // AVAudioSessionCategorySoloAmbient
	IOSSessionCategoryPlayback                                // AVAudioSessionCategoryPlayback
	IOSSessionCategoryRecord                                  // AVAudioSessionCategoryRecord
	IOSSessionCategoryPlayAndRecord                           // AVAudioSessionCategoryPlayAndRecord
	IOSSessionCategoryMultiRoute                              // AVAudioSessionCategoryMultiRoute

IOSSessionCategory enumeration.

type IOSSessionCategoryOptions

type IOSSessionCategoryOptions uint32

IOSSessionCategoryOptions type.

type JackContextConfig

type JackContextConfig struct {
	PClientName    *byte
	TryStartServer uint32
	// contains filtered or unexported fields

JackContextConfig type.

type LogProc

type LogProc func(message string)

LogProc type.

type PerformanceProfile

type PerformanceProfile uint32

PerformanceProfile type.

const (
	LowLatency PerformanceProfile = iota

PerformanceProfile enumeration.

type PulseContextConfig

type PulseContextConfig struct {
	PApplicationName *byte
	PServerName      *byte
	// Enables autospawning of the PulseAudio daemon if necessary.
	TryAutoSpawn uint32
	// contains filtered or unexported fields

PulseContextConfig type.

type PulseDeviceConfig

type PulseDeviceConfig struct {
	StreamNamePlayback *int8
	StreamNameCapture  *int8

PulseDeviceConfig type.

type ResampleAlgorithm

type ResampleAlgorithm uint32

ResampleAlgorithm type.

const (
	ResampleAlgorithmLinear ResampleAlgorithm = 0
	ResampleAlgorithmSpeex  ResampleAlgorithm = 1

ResampleAlgorithm enumeration.

type ResampleConfig

type ResampleConfig struct {
	Algorithm ResampleAlgorithm
	Linear    ResampleLinearConfig
	Speex     ResampleSpeexConfig

ResampleConfig type.

type ResampleLinearConfig

type ResampleLinearConfig struct {
	LpfOrder uint32

ResampleLinearConfig type.

type ResampleSpeexConfig

type ResampleSpeexConfig struct {
	Quality int

ResampleSpeexConfig type.

type Result

type Result int32

Result type.

type ShareMode

type ShareMode uint32

ShareMode type.

const (
	Shared ShareMode = iota

ShareMode enumeration.

type StopProc

type StopProc func()

StopProc type.

type SubConfig

type SubConfig struct {
	DeviceID   unsafe.Pointer
	Format     FormatType
	Channels   uint32
	ChannelMap [C.MA_MAX_CHANNELS]uint8
	ShareMode  ShareMode
	// contains filtered or unexported fields

SubConfig type.

type ThreadPriority

type ThreadPriority int32

ThreadPriority type.

const (
	ThreadPriorityIdle     ThreadPriority = -5
	ThreadPriorityLowest   ThreadPriority = -4
	ThreadPriorityLow      ThreadPriority = -3
	ThreadPriorityNormal   ThreadPriority = -2
	ThreadPriorityHigh     ThreadPriority = -1
	ThreadPriorityHighest  ThreadPriority = 0
	ThreadPriorityRealtime ThreadPriority = 1

	ThreadPriorityDefault ThreadPriority = 0

ThreadPriority enumeration.

type WasapiDeviceConfig

type WasapiDeviceConfig struct {
	NoAutoConvertSRC     uint32
	NoDefaultQualitySRC  uint32
	NoAutoStreamRouting  uint32
	NoHardwareOffloading uint32

WasapiDeviceConfig type.


Path Synopsis
This example simply captures data from your default microphone until you press Enter, after which it plays back the captured audio.
This example simply captures data from your default microphone until you press Enter, after which it plays back the captured audio.

Jump to

Keyboard shortcuts

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