### Playback Example Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/README.md Demonstrates basic audio playback initialization and setup. Ensure you have the necessary context and device configurations. ```go ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, nil) deffer ctx.Free() config := malgo.DefaultDeviceConfig(malgo.Playback) device, _ := malgo.InitDevice(ctx.Context, config, malgo.DeviceCallbacks{ Data: func(out, in []byte, frames uint32) { // Fill 'out' with audio samples }, }) deffer device.Uninit() device.Start() ``` -------------------------------- ### Device.Start Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Starts audio playback or recording on the initialized device. ```APIDOC ## Device.Start ### Description Starts audio playback or recording on the initialized device. ### Signature `Start() error` ### Returns - `error`: An error if starting the device fails. ``` -------------------------------- ### Buffer Size Calculation Example Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md An example demonstrating buffer size calculation for 1024 frames, stereo, and S16 format. ```go // 1024 frames, stereo, S16 frameCount := uint32(1024) channels := uint32(2) sampleSize := malgo.SampleSizeInBytes(malgo.FormatS16) // 2 bufferSize := int(frameCount * channels) * sampleSize // 4096 bytes ``` -------------------------------- ### Check if Device is Started Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Verify if a device has been started before performing operations. This prevents errors when interacting with an uninitialized device. ```go if !device.IsStarted() { fmt.Println("Device is not running") } ``` -------------------------------- ### Example: Iterating Through Devices Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Demonstrates how to retrieve and print information about available playback devices, including their names, IDs, and supported formats. Requires the malgo package. ```go devices, _ := ctx.Devices(malgo.Playback) for _, dev := range devices { fmt.Printf("Device: %s (ID: %v)\n", dev.Name(), dev.ID) fmt.Printf("Formats: %+v\n", dev.Formats) } ``` -------------------------------- ### Start Device Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Activates the audio device. For playback, it starts audio output; for capture, it begins recording. Ensures initial audio data is buffered for playback devices. ```go err := device.Start() if err != nil { log.Fatal(err) } fmt.Println("Device started") ``` -------------------------------- ### Complete Device Enumeration Example Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Enumerates all playback and capture devices, printing their names and supported audio formats for playback devices. ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { log.Fatal(err) } deferrd func() { _ = ctx.Uninit() ctx.Free() }() // List all playback devices playbackDevices, err := ctx.Devices(malgo.Playback) if err != nil { log.Fatal(err) } for i, dev := range playbackDevices { fmt.Printf("Playback Device %d: %s\n", i, dev.Name()) fmt.Printf(" ID: %v\n", dev.ID) fmt.Printf(" Default: %v\n", dev.IsDefault != 0) // Get detailed information detailed, err := ctx.DeviceInfo(malgo.Playback, dev.ID, malgo.Shared) if err != nil { fmt.Printf(" Error getting details: %v\n", err) continue } fmt.Printf(" Supported Formats:\n") for _, format := range detailed.Formats { fmt.Printf(" - %v Hz, %d channels, format %d\n", format.SampleRate, format.Channels, format.Format) } } // List all capture devices captureDevices, err := ctx.Devices(malgo.Capture) if err != nil { log.Fatal(err) } for i, dev := range captureDevices { fmt.Printf("Capture Device %d: %s\n", i, dev.Name()) } ``` -------------------------------- ### Go Callback Registration Example Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Demonstrates how to register Go callback functions for data processing and device stop events with the Malgo device API. ```go InitDevice(ctx, config, DeviceCallbacks{ Data: myDataFunc, Stop: myStopFunc, }) ``` -------------------------------- ### Example: Printing Device ID Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Demonstrates how to retrieve a list of playback devices and print the string representation of the first device's ID. Requires context and malgo package. ```go devices, _ := ctx.Devices(malgo.Playback) if len(devices) > 0 { fmt.Println(devices[0].ID.String()) // e.g., "01020304" } ``` -------------------------------- ### Minimal Malgo Example with WAV Playback Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md A minimal Malgo application that initializes the context, opens a WAV file, and plays it back through the default audio device. It uses a select statement to keep the application running indefinitely. ```go package main import ( "io" "log" "os" "github.com/gen2brain/malgo" ) func main() { ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, nil) defer ctx.Free() file, _ := os.Open("audio.wav") defer file.Close() config := malgo.DefaultDeviceConfig(malgo.Playback) dev, _ := malgo.InitDevice(ctx.Context, config, malgo.DeviceCallbacks{ Data: func(out, _, _ []byte, _ uint32) { io.ReadFull(file, out) }, }) defer dev.Uninit() dev.Start() select {} // Run forever } ``` -------------------------------- ### Internal Synchronization Example Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Demonstrates the use of a mutex for internal synchronization in concurrent operations. ```go var contextMutex sync.Mutex // Internal synchronization ``` -------------------------------- ### Check if Device is Started Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Determines if the audio device is currently active (playing or recording). ```go if device.IsStarted() { fmt.Println("Device is playing/recording") } ``` -------------------------------- ### Get Playback Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the audio format for playback from the device. ```go fmt.Printf("Playback format: %v\n", device.PlaybackFormat()) ``` -------------------------------- ### Get Playback Internal Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the sample format negotiated with the audio backend for playback. ```go fmt.Printf("Playback internal format: %v\n", dev.PlaybackInternalFormat()) ``` -------------------------------- ### Get Capture Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the audio format for capture from the device. ```go fmt.Printf("Capture format: %v\n", device.CaptureFormat()) ``` -------------------------------- ### JackContextConfig Structure Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md JACK backend-specific context configuration. Allows setting the client name and attempting to start the JACK server. ```go type JackContextConfig struct { PClientName *byte TryStartServer uint32 } ``` -------------------------------- ### Configure Malgo for Windows WASAPI Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Example of configuring a playback device for Windows using WASAPI, with an option to disable automatic sample rate conversion. ```go deviceConfig := malgo.DefaultDeviceConfig(malgo.Playback) deviceConfig.Wasapi.NoAutoConvertSRC = 0 // Allow automatic conversion ``` -------------------------------- ### Get Capture Internal Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the sample format negotiated with the audio backend for capture. ```go fmt.Printf("Capture internal format: %v\n", dev.CaptureInternalFormat()) ``` -------------------------------- ### Configure CoreAudio for iOS Playback and Bluetooth Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Example of configuring CoreAudio for iOS, enabling playback and Bluetooth audio. ```go config := malgo.ContextConfig{ CoreAudio: malgo.CoreAudioConfig{ SessionCategory: malgo.IOSSessionCategoryPlayAndRecord, SessionCategoryOptions: malgo.IOSSessionCategoryOptionAllowBluetooth | malgo.IOSSessionCategoryOptionDefaultToSpeaker, }, } ``` -------------------------------- ### Handling Miniaudio Errors Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Example of how to check for and print miniaudio errors using the `Error()` method of the `Result` type. This is useful for debugging and user feedback. ```go if err := someFunc(); err != nil { fmt.Println(err.Error()) // e.g., "miniaudio: Invalid argument" } ``` -------------------------------- ### Initialize Malgo Context with Error Handling Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Demonstrates robust initialization of the Malgo context, including checks for specific errors like no audio backend availability. ```go package main import ( "fmt" "log" "github.com/gen2brain/malgo" ) func main() { // Initialize with error checking ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { // Check for specific errors if err == malgo.ErrNoBackend { log.Fatal("No audio backend available on this system") } log.Fatalf("Context initialization failed: %v", err) } defer func() { _ = ctx.Uninit() ctx.Free() }() // Enumerate devices safely devices, err := ctx.Devices(malgo.Playback) if err != nil { log.Fatalf("Device enumeration failed: %v", err) } if len(devices) == 0 { log.Fatal("No playback devices found") } // Initialize device with error handling config := malgo.DefaultDeviceConfig(malgo.Playback) config.Playback.Channels = 2 config.SampleRate = 44100 config.Playback.Format = malgo.FormatS16 device, err := malgo.InitDevice(ctx.Context, config, malgo.DeviceCallbacks{ Data: func(out, in []byte, frames uint32) { // Minimal callback for testing }, }) if err != nil { // Check for specific device errors if err == malgo.ErrNoDevice { log.Fatal("Specified playback device not found") } if err == malgo.ErrFormatNotSupported { log.Fatal("Audio format not supported by device") } log.Fatalf("Device initialization failed: %v", err) } defer device.Uninit() // Start with error handling if err := device.Start(); err != nil { if err == malgo.ErrFailedToStartBackendDevice { log.Fatal("Backend device failed to start") } log.Fatalf("Device start failed: %v", err) } fmt.Println("Device started successfully") // Stop with error handling if err := device.Stop(); err != nil { log.Printf("Warning: device stop failed: %v", err) } } ``` -------------------------------- ### Initializing Context with Logging Callback Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Demonstrates how to initialize an audio context and set a custom logging procedure using `InitContext`. The provided function will receive log messages. ```go ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, func(msg string) { log.Printf("[audio] %s", msg) }) ``` -------------------------------- ### Initialize Malgo Context and Playback Device Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Demonstrates initializing the Malgo context with custom thread priority and ALSA settings, and configuring a playback device with specific format, channels, sample rate, and performance profile. Includes platform-specific adjustments for ALSA, WASAPI, and PulseAudio. ```go package main import ( "fmt" "log" "github.com/gen2brain/malgo" ) func main() { // Initialize context with custom logging contextConfig := malgo.ContextConfig{ ThreadPriority: malgo.ThreadPriorityHigh, Alsa: malgo.AlsaContextConfig{ UseVerboseDeviceEnumeration: 0, }, } ctx, err := malgo.InitContext(nil, contextConfig, func(msg string) { log.Printf("[audio] %s", msg) }) if err != nil { log.Fatal(err) } defer func() { _ = ctx.Uninit() ctx.Free() }() // Initialize playback device deviceConfig := malgo.DefaultDeviceConfig(malgo.Playback) deviceConfig.Playback.Format = malgo.FormatF32 deviceConfig.Playback.Channels = 2 deviceConfig.SampleRate = 44100 deviceConfig.PerformanceProfile = malgo.LowLatency // Platform-specific adjustments deviceConfig.Alsa.NoMMap = 1 deviceConfig.Wasapi.NoAutoConvertSRC = 0 deviceConfig.Pulse.StreamNamePlayback = "my_app" fmt.Printf("Device config: %+v\n", deviceConfig) } ``` -------------------------------- ### Get Sample Rate Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the sample rate in Hz for the device. ```go sr := device.SampleRate() fmt.Printf("Sample rate: %d Hz\n", sr) ``` -------------------------------- ### Proper Cleanup Order Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Demonstrates the correct sequence for cleaning up Malgo resources, ensuring devices are uninitialized before the context. ```go // Create ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, nil) device, _ := malgo.InitDevice(ctx.Context, config, callbacks) // Use _ = device.Start() _ = device.Stop() // Cleanup (reverse order) device.Uninit() // 1. Uninit device first _ = ctx.Uninit() // 2. Then uninit context ctx.Free() // 3. Then free context ``` -------------------------------- ### Idiomatic Error Handling for Device Initialization Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Demonstrates idiomatic Go error handling for `malgo.InitDevice`, checking for common errors like `malgo.ErrNoDevice` and `malgo.ErrFormatNotSupported`. ```go device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { if err == malgo.ErrNoDevice { return fmt.Errorf("no audio devices available") } if err == malgo.ErrFormatNotSupported { return fmt.Errorf("unsupported audio format") } return fmt.Errorf("device init failed: %w", err) } ``` -------------------------------- ### Initialize Context with Automatic Backend Selection Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Initializes an audio context, allowing the library to automatically select the optimal backend for the current platform. This is the recommended approach for broad compatibility. ```Go // Try all available backends in optimal order for the platform ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, nil) ``` -------------------------------- ### Get Capture Channels Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the number of capture channels configured for the device. ```go fmt.Printf("Capture channels: %d\n", device.CaptureChannels()) ``` -------------------------------- ### Get Playback Channels Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the number of playback channels configured for the device. ```go channels := device.PlaybackChannels() fmt.Printf("Playback channels: %d\n", channels) ``` -------------------------------- ### Initialize Audio Device Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Initializes an audio device with a specified configuration and callbacks. Ensure to uninitialize the device when done using `defer device.Uninit()`. ```go config := malgo.DefaultDeviceConfig(malgo.Playback) config.Playback.Format = malgo.FormatS16 config.Playback.Channels = 2 config.SampleRate = 44100 callbacks := malgo.DeviceCallbacks{ Data: func(pOutputSample, pInputSamples []byte, framecount uint32) { // Fill pOutputSample with audio data }, Stop: func() { fmt.Println("Device stopped") }, } device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { log.Fatal(err) } defers device.Uninit() ``` -------------------------------- ### Get Playback Internal Channels Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the negotiated channel count for audio playback with the backend. ```go func (dev *Device) PlaybackInternalChannels() uint32 ``` -------------------------------- ### Get Capture Internal Channels Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the channel count negotiated with the audio backend for capture. ```go fmt.Printf("Capture internal channels: %d\n", dev.CaptureInternalChannels()) ``` -------------------------------- ### Malgo Initialization Flow Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Illustrates the sequence of calls for initializing a malgo context and device. This involves creating C structures, converting configurations, and storing callbacks. ```Go Application │ ├─ InitContext(backends, config, logProc) │ ├─ Create C.ma_context structure │ ├─ Initialize with selected backends │ ├─ Store log callback │ └─ Return AllocatedContext │ └─ InitDevice(context, config, callbacks) ├─ Create C.ma_device structure ├─ Convert Go DeviceConfig to C ma_device_config ├─ Store Data and Stop callbacks └─ Return Device ``` -------------------------------- ### Create and Customize Default Device Configuration Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Demonstrates obtaining default device configuration and then customizing playback channels, format, sample rate, and ALSA settings. ```go // Get defaults for playback device config := malgo.DefaultDeviceConfig(malgo.Playback) // Customize config.Playback.Channels = 2 config.Playback.Format = malgo.FormatS16 config.SampleRate = 44100 config.Alsa.NoMMap = 1 ``` -------------------------------- ### InitContext Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Creates and initializes an audio backend context. This function is the entry point for using the malgo library and requires a configuration object. ```APIDOC ## InitContext ### Description Creates and initializes a context with specified backends and configuration. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * `backends` ([]Backend) - Optional - List of backend types to try. If nil or empty, tries all available backends. * `config` (ContextConfig) - Required - Configuration object for context initialization. * `logProc` (LogProc) - Optional - Callback function for logging messages. Signature: `func(message string)`. ### Response #### Success Response (200) * `(*AllocatedContext, error)` - Returns an `AllocatedContext` that must be freed after use, or an error. #### Error Response * `ErrOutOfMemory` - Insufficient memory to allocate context. * Various backend-specific errors - Backend initialization failed. ### Example ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{ ThreadPriority: malgo.ThreadPriorityDefault, }, func(message string) { fmt.Printf("LOG: %v\n", message) }) if err != nil { log.Fatal(err) } defer func() { _ = ctx.Uninit() ctx.Free() }() ``` ``` -------------------------------- ### Initialize Context with Specific Backends Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Initializes an audio context by attempting to use a specified list of backends in order. Useful for prioritizing certain audio APIs. ```Go backends := []malgo.Backend{ malgo.BackendPulseaudio, malgo.BackendAlsa, malgo.BackendJack, } ctx, _ := malgo.InitContext(backends, malgo.ContextConfig{}, nil) ``` -------------------------------- ### Get Default Playback Device ID Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Retrieves the ID of the default playback device. The first device in the list is typically the default. ```go devices, _ := ctx.Devices(malgo.Playback) defaultID := devices[0].ID // First device is usually default ``` -------------------------------- ### Use Default Context for Device Initialization Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Initializes an audio device using the `DefaultContext`, which applies implicit context defaults. This is a convenient way to set up devices without explicit context configuration. ```go device, err := malgo.InitDevice(malgo.DefaultContext, deviceConfig, callbacks) ``` -------------------------------- ### Android AAudio/OpenSL Initialization Flow Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Explains the initialization process for context and device on Android, covering both AAudio and OpenSL ES. ```text InitContext │ ├─ AAudio (API 28+) │ └─ AAudioStreamBuilder_create() │ └─ OpenSL (fallback) └─ SLEngineItf_CreateAudioPlayer/Recorder() InitDevice ├─ AAudio: AAudioStreamBuilder_build() │ └─ Configure usage, content type, presets │ └─ OpenSL: IPlay_SetPlayState() ``` -------------------------------- ### Stop Device Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Puts the device into a dormant state without uninitializing it. Call `Start()` to resume. This operation waits for the backend device to stop processing. ```go err := device.Stop() if err != nil { log.Fatal(err) } fmt.Println("Device stopped") ``` -------------------------------- ### Device.Start Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Activates the device, initiating playback or recording. For playback devices, it retrieves an initial chunk of audio data to ensure the buffer is valid before returning. ```APIDOC ## Device.Start ### Description Activates the device. For playback devices, begins playback. For capture devices, begins recording. Retrieves an initial chunk of audio data from the client before returning to ensure valid audio data is in the buffer. ### Method POST (implied) ### Endpoint N/A (Method call) ### Return Type `error` - Returns `nil` on success. ### Errors - `ErrDeviceNotInitialized`: Device has not been initialized. - `ErrFailedToStartBackendDevice`: Backend failed to start the device. ### Example ```go err := device.Start() if err != nil { log.Fatal(err) } fmt.Println("Device started") ``` ``` -------------------------------- ### Initialize malgo Context Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Initializes a malgo audio context. It's recommended to use `nil` for backends to try all available options and provide a logging callback. The returned context must be freed after use. ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{ ThreadPriority: malgo.ThreadPriorityDefault, }, func(message string) { fmt.Printf("LOG: %v\n", message) }) if err != nil { log.Fatal(err) } defer func() { _ = ctx.Uninit() ctx.Free() }() ``` -------------------------------- ### InitDevice Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Initializes an audio device for playback or capture, based on the provided configuration and callbacks. ```APIDOC ## InitDevice ### Description Initializes an audio device for playback or capture, based on the provided configuration and callbacks. ### Signature `InitDevice(Context, DeviceConfig, DeviceCallbacks) (*Device, error)` ### Parameters #### Path Parameters - `Context` (Context) - Required - The audio context to use. - `DeviceConfig` (DeviceConfig) - Required - Configuration for the audio device. - `DeviceCallbacks` (DeviceCallbacks) - Required - Callbacks for data processing and device stop events. ### Returns - `*Device`: An initialized device object. - `error`: An error if initialization fails. ``` -------------------------------- ### Get Playback Internal Sample Rate Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the actual sample rate negotiated with the audio backend for playback. This may differ from the requested rate. ```go fmt.Printf("Playback internal sample rate: %d Hz\n", dev.PlaybackInternalSampleRate()) ``` -------------------------------- ### Get Capture Internal Sample Rate Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Retrieves the actual sample rate negotiated with the audio backend for capture. This may differ from the requested rate. ```go fmt.Printf("Capture internal sample rate: %d Hz\n", dev.CaptureInternalSampleRate()) ``` -------------------------------- ### Backend Enumeration Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Defines the available audio backends. Used with InitContext() to select backends for context initialization. ```go type Backend uint32 const ( BackendWasapi Backend = iota // Windows WASAPI BackendDsound // Windows DirectSound BackendWinmm // Windows WinMM BackendCoreaudio // macOS/iOS CoreAudio BackendSndio // OpenBSD/NetBSD sndio BackendAudio4 // NetBSD audio(4) BackendOss // Linux/BSD OSS BackendPulseaudio // Linux PulseAudio BackendAlsa // Linux ALSA BackendJack // Cross-platform JACK BackendAaudio // Android AAudio BackendOpensl // Android OpenSL|ES BackendWebaudio // Web Audio API BackendNull // Null/silent backend ) ``` -------------------------------- ### Windows WASAPI Initialization Flow Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Outlines the steps involved in initializing the context and device using the WASAPI backend on Windows. ```text InitContext │ └─ Try WASAPI backend ├─ Create IAudioClient ├─ Create IAudioRenderClient (playback) ├─ Create IAudioCaptureClient (capture) └─ Initialize event loop InitDevice │ └─ Setup WASAPI format ├─ WAVEFORMATEX configuration ├─ Buffer and period management └─ Start/stop event loop ``` -------------------------------- ### Device.Stop Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Puts the device into a sleep state without uninitializing it. Call `Start()` to resume operation. This method waits for the worker thread to properly stop the backend device. ```APIDOC ## Device.Stop ### Description Puts the device to sleep without uninitialization. Call `Start()` to resume. This API waits for the worker thread to stop the backend device properly. Some backends may wait for the device to finish playback/recording of the current fragment. ### Method POST (implied) ### Endpoint N/A (Method call) ### Return Type `error` - Returns `nil` on success. ### Errors - `ErrDeviceNotInitialized`: Device has not been initialized. - `ErrFailedToStopBackendDevice`: Backend failed to stop the device. ### Example ```go err := device.Stop() if err != nil { log.Fatal(err) } fmt.Println("Device stopped") ``` ``` -------------------------------- ### Full-Duplex Audio Operation Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Performs simultaneous audio playback and capture. This example demonstrates a simple pass-through where input is echoed to output. Adjust formats and channels as needed. ```go package main import ( "fmt" "log" "github.com/gen2brain/malgo" ) func main() { // Initialize context ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { log.Fatal(err) } defer func() { _ = ctx.Uninit() ctx.Free() }() // Configure duplex device (simultaneous input and output) config := malgo.DefaultDeviceConfig(malgo.Duplex) config.Playback.Format = malgo.FormatF32 config.Playback.Channels = 2 config.Capture.Format = malgo.FormatF32 config.Capture.Channels = 2 config.SampleRate = 48000 // Define callback for simultaneous input/output processing callbacks := malgo.DeviceCallbacks{ Data: func(pOutputSample, pInputSamples []byte, framecount uint32) { // In a real application, you would process the input samples // and write processed output samples if len(pInputSamples) > 0 && len(pOutputSample) > 0 { // Simple pass-through: echo the input to output copy(pOutputSample, pInputSamples) } }, } // Initialize device device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { log.Fatal(err) } defer device.Uninit() // Start duplex operation if err := device.Start(); err != nil { log.Fatal(err) } fmt.Println("Full-duplex running... Press Enter to stop") fmt.Scanln() if err := device.Stop(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Linux ALSA/PulseAudio Initialization Flow Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Describes the context and device initialization process on Linux, prioritizing PulseAudio and falling back to ALSA. ```text InitContext with Priority Selection ├─ Try PulseAudio first (if available) │ ├─ pa_context_new() │ ├─ pa_context_connect() │ └─ Async operation loop │ └─ Fallback to ALSA ├─ snd_card_next() ├─ snd_ctl_card_info() └─ List devices via PCM nodes InitDevice ├─ PulseAudio: pa_stream_new() + pa_stream_connect_*() └─ ALSA: snd_pcm_open() + snd_pcm_hw_params_set_*() ``` -------------------------------- ### Malgo Error Handling Pattern Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/errors.md Demonstrates how to initialize the Malgo context and handle potential errors, including specific error checks for backend availability. ```go import "github.com/gen2brain/malgo" func example() error { ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { // err is of type malgo.Result if err == malgo.ErrNoBackend { // Handle specific error return fmt.Errorf("no audio backend available") } return fmt.Errorf("failed to init context: %v", err) } defer func() { _ = ctx.Uninit() ctx.Free() }() return nil } ``` -------------------------------- ### Create Default Device Configurations Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Generate default device configurations for playback, capture, and duplex audio devices. These configurations provide sensible defaults for sample rate, performance profile, and platform-specific settings. ```go playbackConfig := malgo.DefaultDeviceConfig(malgo.Playback) captureConfig := malgo.DefaultDeviceConfig(malgo.Capture) duplexConfig := malgo.DefaultDeviceConfig(malgo.Duplex) ``` -------------------------------- ### Get Specific Device Info Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Retrieves detailed information for a specific audio device, including its supported formats. Requires the device type, ID, and share mode (Shared or Exclusive). ```go devices, err := ctx.Devices(malgo.Playback) if err != nil { log.Fatal(err) } if len(devices) > 0 { info, err := ctx.DeviceInfo(malgo.Playback, devices[0].ID, malgo.Shared) if err != nil { log.Fatal(err) } fmt.Printf("Formats: %+v\n", info.Formats) } ``` -------------------------------- ### Initialize malgo Context with Default Thread Priority Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Basic initialization of a malgo audio context using default thread priority. ```go config := malgo.ContextConfig{ ThreadPriority: malgo.ThreadPriorityDefault, } ctx, err := malgo.InitContext(nil, config, nil) ``` -------------------------------- ### Get Sample Size in Bytes for Float32 Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Determine the size of a single audio sample in bytes for the FormatF32 audio format. This utility function is helpful for understanding memory requirements for audio data. ```go formatSize := malgo.SampleSizeInBytes(malgo.FormatF32) // returns 4 ``` -------------------------------- ### Configure Device with ID Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Sets up a device configuration using a specific device ID for playback. ```go config := malgo.DefaultDeviceConfig(malgo.Playback) config.Playback.DeviceID = unsafe.Pointer(devices[0].ID.cptr()) device, _ := malgo.InitDevice(ctx.Context, config, callbacks) ``` -------------------------------- ### Buffer Slicing in C and Go Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Illustrates how to calculate the total byte size of a buffer in C and then convert it to a Go byte slice using unsafe.Slice. ```text C void* pointer │ ├─ Calculate total byte size │ └─ frames × channels × bytes_per_sample │ └─ Convert to Go []byte └─ unsafe.Slice((*byte)(ptr), size_in_bytes) ``` -------------------------------- ### Idiomatic Error Handling for Context Initialization Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Shows idiomatic Go error handling for `malgo.InitContext`, including specific checks for `malgo.ErrNoBackend`. ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { if err == malgo.ErrNoBackend { return fmt.Errorf("no audio backends available") } return fmt.Errorf("context init failed: %w", err) } ``` -------------------------------- ### macOS/iOS CoreAudio Initialization Flow Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Details the initialization steps for context and device on macOS/iOS using CoreAudio, including session category configuration. ```text InitContext │ └─ Configure iOS session category ├─ AVAudioSession singleton ├─ Set category + options └─ Handle interruptions InitDevice ├─ AudioUnitComponent creation ├─ AudioUnit initialization ├─ Format configuration via StreamBasicDescription └─ Render callback setup ``` -------------------------------- ### Check Device Capabilities and Fallback Format Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Demonstrates how to check if a specific audio device configuration is supported and attempts to use a fallback format (F32) if the initial format (S16) is not supported. ```go config := malgo.DefaultDeviceConfig(malgo.Playback) // Check if requested configuration is supported device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { if err == malgo.ErrFormatNotSupported { // Try different format config.Playback.Format = malgo.FormatF32 device, err = malgo.InitDevice(ctx.Context, config, callbacks) } } ``` -------------------------------- ### Configure Playback Device Format and Channels Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/configuration.md Set the audio format to signed 16-bit PCM and specify 2 channels for playback. ```go config := malgo.DefaultDeviceConfig(malgo.Playback) config.Playback.Format = malgo.FormatS16 config.Playback.Channels = 2 config.Playback.ShareMode = malgo.Shared ``` -------------------------------- ### List Documentation Files Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/INDEX.md This command lists all available markdown documentation files within the output directory. It's useful for understanding the scope of the provided documentation. ```bash ls /workspace/home/output/*.md ``` -------------------------------- ### Basic Audio Playback Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Plays an audio file (e.g., audio.wav) using the default playback device. Ensure the audio file is in the same directory as the executable. ```go package main import ( "fmt" "io" "log" "os" "github.com/gen2brain/malgo" ) func main() { // Initialize context ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { log.Fatal(err) } defer func() { _ = ctx.Uninit() ctx.Free() }() // Open audio file file, err := os.Open("audio.wav") if err != nil { log.Fatal(err) } defer file.Close() // Configure device config := malgo.DefaultDeviceConfig(malgo.Playback) config.Playback.Format = malgo.FormatS16 config.Playback.Channels = 2 config.SampleRate = 44100 // Define data callback callbacks := malgo.DeviceCallbacks{ Data: func(pOutputSample, pInputSamples []byte, framecount uint32) { _, _ = io.ReadFull(file, pOutputSample) }, } // Initialize device device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { log.Fatal(err) } defer device.Uninit() // Start playback if err := device.Start(); err != nil { log.Fatal(err) } fmt.Println("Playing... Press Enter to stop") fmt.Scanln() if err := device.Stop(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Go Callback to C Wrapper Conversion Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Explains how Go callback functions are wrapped and registered with C, including map storage and type conversion upon invocation. ```text Go Callback (DataProc) │ ├─ C wrapper function (goDataCallback exported) ├─ Store Go callback in thread-safe map ├─ Register C wrapper with C device └─ When invoked: ├─ C calls goDataCallback ├─ Look up Go callback ├─ Convert C types to Go types │ └─ C pointers → Go slices via unsafe.Slice() └─ Invoke Go callback ``` -------------------------------- ### Context.Uninit Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Uninitializes the audio context, releasing associated resources. ```APIDOC ## Context.Uninit ### Description Uninitializes the audio context, releasing associated resources. ### Signature `Uninit() error` ### Returns - `error`: An error if uninitialization fails. ``` -------------------------------- ### Define Device Callbacks Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Sets up callback functions for device events, including data processing for full-duplex I/O and an optional callback for when the device stops. ```go type DeviceCallbacks struct { Data DataProc Stop StopProc } ``` ```go type DataProc func(pOutputSample, pInputSamples []byte, framecount uint32) ``` ```go type StopProc func() ``` ```go callbacks := malgo.DeviceCallbacks{ Data: func(out, in []byte, frames uint32) { // Generate or process audio if len(out) > 0 { // Fill output buffer with audio data copy(out, audioBuffer) } }, Stop: func() { fmt.Println("Device stopped") }, } ``` -------------------------------- ### ContextConfig Structure Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Configuration structure for initializing the Malgo context. Allows setting up logging, thread priority, and backend-specific options. ```go type ContextConfig struct { LogCallback *[0]byte ThreadPriority ThreadPriority PUserData *byte AllocationCallbacks AllocationCallbacks Alsa AlsaContextConfig Pulse PulseContextConfig CoreAudio CoreAudioConfig Jack JackContextConfig } ``` -------------------------------- ### Log Audio Events with Custom Callback Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/quick-start-guide.md Initializes the Malgo context with a custom logging callback function to capture and log messages from the audio system. Also shows how to log device data processing and stop events. ```go ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, func(msg string) { log.Printf("[AUDIO] %s", msg) }) defunc() { _ = ctx.Uninit() ctx.Free() }() callbacks := malgo.DeviceCallbacks{ Data: func(out, in []byte, frames uint32) { log.Printf("Processing %d frames", frames) }, Stop: func() { log.Println("Device stopped") }, } ``` -------------------------------- ### InitContext Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Initializes the audio context, which is necessary for any audio operations. It allows specifying backends and logging behavior. ```APIDOC ## InitContext ### Description Initializes the audio context, which is necessary for any audio operations. It allows specifying backends and logging behavior. ### Signature `InitContext([]Backend, ContextConfig, LogProc) (*AllocatedContext, error)` ### Returns - `*AllocatedContext`: An initialized context object. - `error`: An error if initialization fails. ``` -------------------------------- ### Resource Management with Defer Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Utilizes `defer` statements to ensure proper cleanup of Malgo context and device resources, even in the presence of errors. ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { return err } deferrd func() { _ = ctx.Uninit() ctx.Free() }() device, err := malgo.InitDevice(ctx.Context, config, callbacks) if err != nil { return err } deferrd device.Uninit() // ... use device ... ``` -------------------------------- ### Go Structure to C Conversion Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Illustrates the process of converting Go structure types to their C equivalents, involving initialization and field-by-field copying. ```text Go ContextConfig │ ├─ Create C.ma_context_config via C.ma_context_config_init() ├─ Field-by-field copy from Go to C │ ├─ Simple types: direct cast │ ├─ Pointers: unsafe.Pointer conversion │ └─ Nested structs: recursive conversion └─ Pass to C function ``` -------------------------------- ### Device.Uninit Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Uninitializes the audio device, releasing associated resources. ```APIDOC ## Device.Uninit ### Description Uninitializes the audio device, releasing associated resources. ### Signature `Uninit()` ``` -------------------------------- ### Initialize Malgo Context with Custom Logging Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Initialize the Malgo context and provide a custom callback function for logging messages. This allows for centralized logging of library events. ```go ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, func(message string) { fmt.Printf("[miniaudio] %s\n", message) }) ``` -------------------------------- ### Define DeviceConfig Structure Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Defines the main structure for device initialization configuration, including sample rate, period size, performance profile, and platform-specific settings. ```go 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 AAudio AAudioDeviceConfig } ``` -------------------------------- ### Context.Uninit Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Uninitializes the audio context, releasing associated resources. This should be called after all devices created by the context are no longer active. ```APIDOC ## Context.Uninit ### Description Uninitializes a context. Results are undefined if called while any device created by this context is still active. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Response #### Success Response (200) * `error` - Returns `nil` on success. #### Error Response * An error code if uninitialization failed. ### Example ```go err := ctx.Uninit() if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### PulseContextConfig Structure Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md PulseAudio backend-specific context configuration. Allows setting application name, server name, and auto-spawning the daemon. ```go type PulseContextConfig struct { PApplicationName *byte PServerName *byte TryAutoSpawn uint32 } ``` -------------------------------- ### Context.Devices Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/module-index.md Lists all available audio devices of a specified type. ```APIDOC ## Context.Devices ### Description Lists all available audio devices of a specified type. ### Signature `Devices(DeviceType) ([]DeviceInfo, error)` ### Parameters #### Path Parameters - `DeviceType` (DeviceType) - Required - The type of devices to list. ### Returns - `[]DeviceInfo`: A slice of available device information. - `error`: An error if listing devices fails. ``` -------------------------------- ### List Playback Devices Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Retrieves a list of available playback devices. The output includes device metadata and supported audio formats. Errors during enumeration are returned. ```go devices, err := ctx.Devices(malgo.Playback) if err != nil { log.Fatal(err) } for _, dev := range devices { fmt.Printf("Device: %s (ID: %v)\n", dev.Name(), dev.ID) } ``` -------------------------------- ### Device.PlaybackInternalFormat Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Returns the sample format negotiated with the audio backend for playback. ```APIDOC ## Device.PlaybackInternalFormat ### Description Returns the sample format negotiated with the audio backend for playback. ### Method (Method receiver: `dev *Device`) ### Endpoint (N/A - Method call) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Response #### Success Response - **FormatType** (`FormatType`) - The negotiated playback sample format. ``` -------------------------------- ### Initialize Malgo Context with Debug Logging Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/architecture.md Initializes the Malgo context and sets up a callback function to log debug messages. This is useful for troubleshooting. ```go ctx, _ := malgo.InitContext(nil, malgo.ContextConfig{}, func(msg string) { log.Printf("[malgo] %s", msg) }) ``` -------------------------------- ### Initialize Context Preferring PulseAudio on Linux Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-utility.md Initialize the Malgo context on Linux, explicitly preferring PulseAudio over ALSA for audio playback. This ensures better system integration and volume control. ```go // Prefer PulseAudio if available backends := []malgo.Backend{ malgo.BackendPulseaudio, malgo.BackendAlsa, } ctx, _ := malgo.InitContext(backends, malgo.ContextConfig{}, nil) ``` -------------------------------- ### DeviceInfo String Method Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Returns a formatted string representation of the DeviceInfo. This method is part of the DeviceInfo structure. ```go func (d *DeviceInfo) String() string ``` -------------------------------- ### Free AllocatedContext Resources Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-context.md Demonstrates the correct usage of the Free method to release resources associated with an AllocatedContext. Ensure Free is called exactly once after initialization. ```go ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, nil) if err != nil { log.Fatal(err) } deffer ctx.Free() ``` -------------------------------- ### ContextConfig Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md Configuration structure for initializing the malgo context, including logging, thread priority, and backend-specific settings. ```APIDOC ## ContextConfig Context initialization configuration structure. ### Fields | Field | Type | Default | Description | |-------|------|---------|-------------| | `LogCallback` | `*[0]byte` | `nil` | Callback for context logging (set via SetLogProc) | | `ThreadPriority` | `ThreadPriority` | `ThreadPriorityDefault` | Priority of worker thread | | `PUserData` | `*byte` | `nil` | User-defined pointer | | `AllocationCallbacks` | `AllocationCallbacks` | zero | Custom memory allocation callbacks | | `Alsa` | `AlsaContextConfig` | zero | ALSA backend options | | `Pulse` | `PulseContextConfig` | zero | PulseAudio backend options | | `CoreAudio` | `CoreAudioConfig` | zero | CoreAudio (macOS/iOS) options | | `Jack` | `JackContextConfig` | zero | JACK backend options | ``` -------------------------------- ### Device.Uninit Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Uninitializes the device and releases all associated resources. This action explicitly stops the device; calling `Stop()` beforehand is optional. ```APIDOC ## Device.Uninit ### Description Uninitializes a device and releases resources. This explicitly stops the device; calling `Stop()` beforehand is unnecessary but harmless. ### Method DELETE (implied) ### Endpoint N/A (Method call) ### Example ```go device.Uninit() ``` ``` -------------------------------- ### Uninitialize Device Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/api-reference-device.md Releases all resources associated with the device and stops it. Explicitly calling `Stop()` before `Uninit()` is not required. ```go device.Uninit() ``` -------------------------------- ### PulseContextConfig Source: https://github.com/gen2brain/malgo/blob/master/_autodocs/types.md PulseAudio backend-specific configuration for the malgo context. ```APIDOC ## PulseContextConfig PulseAudio backend-specific context configuration. ### Fields | Field | Type | Description | |-------|------|-------------| | `PApplicationName` | `*byte` | Application name for PulseAudio | | `PServerName` | `*byte` | PulseAudio server name | | `TryAutoSpawn` | `uint32` | Auto-spawn daemon if needed | ```