malgo

package module
v0.11.22 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Unlicense Imports: 6 Imported by: 103

README

malgo

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.

Installation

go get -u github.com/gen2brain/malgo

Documentation

Documentation on GoDoc. Also check examples.

Platforms

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

Documentation

Overview

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

Index

Constants

View Source
const (
	BackendWasapi = iota
	BackendDsound
	BackendWinmm
	BackendCoreaudio
	BackendSndio
	BackendAudio4
	BackendOss
	BackendPulseaudio
	BackendAlsa
	BackendJack
	BackendAaudio
	BackendOpensl
	BackendWebaudio
	BackendNull
)

Backend enumeration.

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.

Variables

View Source
var (
	//  General errors.
	ErrGeneric                    = Result(C.MA_ERROR)
	ErrInvalidArgs                = Result(C.MA_INVALID_ARGS)
	ErrInvalidOperation           = Result(C.MA_INVALID_OPERATION)
	ErrOutOfMemory                = Result(C.MA_OUT_OF_MEMORY)
	ErrOutOfRange                 = Result(C.MA_OUT_OF_RANGE)
	ErrAccessDenied               = Result(C.MA_ACCESS_DENIED)
	ErrDoesNotExist               = Result(C.MA_DOES_NOT_EXIST)
	ErrAlreadyExists              = Result(C.MA_ALREADY_EXISTS)
	ErrTooManyOpenFiles           = Result(C.MA_TOO_MANY_OPEN_FILES)
	ErrInvalidFile                = Result(C.MA_INVALID_FILE)
	ErrTooBig                     = Result(C.MA_TOO_BIG)
	ErrPathTooLong                = Result(C.MA_PATH_TOO_LONG)
	ErrNameTooLong                = Result(C.MA_NAME_TOO_LONG)
	ErrNotDirectory               = Result(C.MA_NOT_DIRECTORY)
	ErrIsDirectory                = Result(C.MA_IS_DIRECTORY)
	ErrDirectoryNotEmpty          = Result(C.MA_DIRECTORY_NOT_EMPTY)
	ErrAtEnd                      = Result(C.MA_AT_END)
	ErrNoSpace                    = Result(C.MA_NO_SPACE)
	ErrBusy                       = Result(C.MA_BUSY)
	ErrIO                         = Result(C.MA_IO_ERROR)
	ErrInterrupt                  = Result(C.MA_INTERRUPT)
	ErrUnavailable                = Result(C.MA_UNAVAILABLE)
	ErrAlreadyInUse               = Result(C.MA_ALREADY_IN_USE)
	ErrBadAddress                 = Result(C.MA_BAD_ADDRESS)
	ErrBadSeek                    = Result(C.MA_BAD_SEEK)
	ErrBadPipe                    = Result(C.MA_BAD_PIPE)
	ErrDeadlock                   = Result(C.MA_DEADLOCK)
	ErrTooManyLinks               = Result(C.MA_TOO_MANY_LINKS)
	ErrNotImplemented             = Result(C.MA_NOT_IMPLEMENTED)
	ErrNoMessage                  = Result(C.MA_NO_MESSAGE)
	ErrBadMessage                 = Result(C.MA_BAD_MESSAGE)
	ErrNoDataAvailable            = Result(C.MA_NO_DATA_AVAILABLE)
	ErrInvalidData                = Result(C.MA_INVALID_DATA)
	ErrTimeout                    = Result(C.MA_TIMEOUT)
	ErrNetwork                    = Result(C.MA_NO_NETWORK)
	ErrNotUnique                  = Result(C.MA_NOT_UNIQUE)
	ErrNotSocket                  = Result(C.MA_NOT_SOCKET)
	ErrNoAddress                  = Result(C.MA_NO_ADDRESS)
	ErrBadProtocol                = Result(C.MA_BAD_PROTOCOL)
	ErrProtocolUnavailable        = Result(C.MA_PROTOCOL_UNAVAILABLE)
	ErrProtocolNotSupported       = Result(C.MA_PROTOCOL_NOT_SUPPORTED)
	ErrProtocolFamilyNotSupported = Result(C.MA_PROTOCOL_FAMILY_NOT_SUPPORTED)
	ErrAddressFamilyNotSupported  = Result(C.MA_ADDRESS_FAMILY_NOT_SUPPORTED)
	ErrSocketNotSupported         = Result(C.MA_SOCKET_NOT_SUPPORTED)
	ErrConnectionReset            = Result(C.MA_CONNECTION_RESET)
	ErrAlreadyConnected           = Result(C.MA_ALREADY_CONNECTED)
	ErrNotConnected               = Result(C.MA_NOT_CONNECTED)
	ErrConnectionRefused          = Result(C.MA_CONNECTION_REFUSED)
	ErrNoHost                     = Result(C.MA_NO_HOST)
	ErrInProgress                 = Result(C.MA_IN_PROGRESS)
	ErrCancelled                  = Result(C.MA_CANCELLED)
	ErrMemoryAlreadyMapped        = Result(C.MA_MEMORY_ALREADY_MAPPED)

	// General miniaudio-specific errors.
	ErrFormatNotSupported     = Result(C.MA_FORMAT_NOT_SUPPORTED)
	ErrDeviceTypeNotSupported = Result(C.MA_DEVICE_TYPE_NOT_SUPPORTED)
	ErrShareModeNotSupported  = Result(C.MA_SHARE_MODE_NOT_SUPPORTED)
	ErrNoBackend              = Result(C.MA_NO_BACKEND)
	ErrNoDevice               = Result(C.MA_NO_DEVICE)
	ErrAPINotFound            = Result(C.MA_API_NOT_FOUND)
	ErrInvalidDeviceConfig    = Result(C.MA_INVALID_DEVICE_CONFIG)
	ErrLoop                   = Result(C.MA_LOOP)

	ErrDeviceNotInitialized     = Result(C.MA_DEVICE_NOT_INITIALIZED)
	ErrDeviceAlreadyInitialized = Result(C.MA_DEVICE_ALREADY_INITIALIZED)
	ErrDeviceNotStarted         = Result(C.MA_DEVICE_NOT_STARTED)
	ErrDeviceNotStopped         = Result(C.MA_DEVICE_NOT_STOPPED)

	ErrFailedToInitBackend        = Result(C.MA_FAILED_TO_INIT_BACKEND)
	ErrFailedToOpenBackendDevice  = Result(C.MA_FAILED_TO_OPEN_BACKEND_DEVICE)
	ErrFailedToStartBackendDevice = Result(C.MA_FAILED_TO_START_BACKEND_DEVICE)
	ErrFailedToStopBackendDevice  = Result(C.MA_FAILED_TO_STOP_BACKEND_DEVICE)
)

Functions

func SampleSizeInBytes

func SampleSizeInBytes(format FormatType) int

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

Types

type AllocatedContext

type AllocatedContext struct {
	Context
	// contains filtered or unexported fields
}

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
	NoAutoChannels uint32
	NoAutoResample uint32
}

AlsaDeviceConfig type.

type Backend

type Backend uint32

Backend type.

type Context

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

Context is used for selecting and initializing the relevant backends.

var DefaultContext Context = Context{}

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 DataFormat added in v0.11.10

type DataFormat struct {
	Format     FormatType
	Channels   uint32
	SampleRate uint32
	Flags      uint32
}

type DataProc

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

DataProc type.

type Device

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

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
	NoPreSilencedOutputBuffer uint32
	NoClip                    uint32
	NoDisableDenormals        uint32
	NoFixedSizedCallback      uint32
	DataCallback              *[0]byte
	NotificationCallback      *[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     []DataFormat
	// 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
	Capture
	Duplex
	Loopback
)

DeviceType enumeration.

type FormatType

type FormatType uint32

FormatType type.

const (
	FormatUnknown FormatType = iota
	FormatU8
	FormatS16
	FormatS24
	FormatS32
	FormatF32
)

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
}

JackContextConfig type.

type LogProc

type LogProc func(message string)

LogProc type.

type PerformanceProfile

type PerformanceProfile uint32

PerformanceProfile type.

const (
	LowLatency PerformanceProfile = iota
	Conservative
)

PerformanceProfile enumeration.

type PulseContextConfig

type PulseContextConfig struct {
	PApplicationName *byte
	PServerName      *byte
	// Enables autospawning of the PulseAudio daemon if necessary.
	TryAutoSpawn uint32
}

PulseContextConfig type.

type PulseDeviceConfig

type PulseDeviceConfig struct {
	StreamNamePlayback string
	StreamNameCapture  string
}

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
}

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.

func (Result) Error added in v0.11.10

func (self Result) Error() string

type ShareMode

type ShareMode uint32

ShareMode type.

const (
	Shared ShareMode = iota
	Exclusive
)

ShareMode enumeration.

type StopProc

type StopProc func()

StopProc type.

type SubConfig

type SubConfig struct {
	DeviceID   unsafe.Pointer
	Format     FormatType
	Channels   uint32
	ChannelMap unsafe.Pointer
	ShareMode  ShareMode
}

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.

Directories

Path Synopsis
_examples
capture
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