### Serve Examples Locally Source: https://github.com/mrdimas/tinyaudio/blob/main/wasm-examples/README.md Start a local HTTP server in the wasm-examples directory to serve the built WebAssembly files. ```bash basic-http-server ``` -------------------------------- ### Install basic-http-server Source: https://github.com/mrdimas/tinyaudio/blob/main/wasm-examples/README.md Install a simple HTTP server for serving static files. ```bash cargo install basic-http-server ``` -------------------------------- ### Run Output Device with Sine Wave Source: https://context7.com/mrdimas/tinyaudio/llms.txt Create and start the audio output device using `run_output_device`. The provided callback fills an interleaved f32 sample buffer. The device plays as long as the returned `OutputDevice` handle is alive. This example plays a 440 Hz sine wave for 5 seconds. ```rust use tinyaudio::prelude::*; fn main() { let params = OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }; // Play a 440 Hz sine wave for 5 seconds let _device = run_output_device(params, { let mut clock = 0f32; move |data| { // `data` is an interleaved buffer: [L0, R0, L1, R1, ...] for samples in data.chunks_mut(params.channels_count) { clock = (clock + 1.0) % params.sample_rate as f32; let value = (clock * 440.0 * 2.0 * std::f32::consts::PI / params.sample_rate as f32).sin(); for sample in samples { *sample = value; } } } }) .unwrap(); // Returns Err if the platform audio device cannot be opened std::thread::sleep(std::time::Duration::from_secs(5)); // _device is dropped here → audio stops and all resources are released } ``` -------------------------------- ### Build WebAssembly Example Source: https://github.com/mrdimas/tinyaudio/blob/main/wasm-examples/README.md Build the Rust project into a WebAssembly module for web deployment. ```bash wasm-pack build --target web --release ``` -------------------------------- ### Install wasm-pack Source: https://github.com/mrdimas/tinyaudio/blob/main/wasm-examples/README.md Install the wasm-pack tool for building Rust to WebAssembly. ```bash cargo install wasm-pack ``` -------------------------------- ### Install PulseAudio Development Files Source: https://context7.com/mrdimas/tinyaudio/llms.txt Install the necessary development files for the PulseAudio backend on Debian-based systems. ```bash sudo apt-get install libpulse-dev ``` -------------------------------- ### Install Rust Target Source: https://github.com/mrdimas/tinyaudio/blob/main/wasm-examples/README.md Ensure the wasm32-unknown-unknown target is installed for Rust. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### run_output_device Source: https://context7.com/mrdimas/tinyaudio/llms.txt Creates and starts an audio output device using the provided parameters and a data callback. The device remains active as long as the returned OutputDevice handle is alive. ```APIDOC ## Function: run_output_device ### Description Opens the default audio output device and begins streaming audio generated by the provided `data_callback`. The callback is responsible for filling an interleaved `f32` sample buffer. ### Parameters - **params** (OutputDeviceParameters) - Required - Configuration for the audio stream. - **data_callback** (FnMut( &mut [f32]) -> ()) - Required - A closure that receives a mutable slice of interleaved `f32` samples and must fill it with audio data. ### Returns - `Result>` - An `OutputDevice` handle if successful, or an error if the audio device cannot be opened. ``` -------------------------------- ### Install cargo-lipo Source: https://github.com/mrdimas/tinyaudio/blob/main/ios-example/README.md Install the cargo-lipo tool, which is required for building universal Rust libraries for iOS. ```bash cargo install cargo-lipo ``` -------------------------------- ### Linux System Dependencies for ALSA Source: https://context7.com/mrdimas/tinyaudio/llms.txt Installs necessary development libraries for the ALSA backend on Linux systems. ```bash # ALSA backend (default) sudo apt-get install libasound2-dev libudev-dev pkg-config ``` -------------------------------- ### Play Sine Wave with TinyAudio Source: https://github.com/mrdimas/tinyaudio/blob/main/README.md Example of playing a 440 Hz sine wave using TinyAudio. It configures the output device and provides a callback that generates sine wave samples. The callback updates a clock to produce the audio signal. Note the use of `std::thread::sleep` to keep the audio playing for a specified duration. ```rust # use tinyaudio::prelude::*; let params = OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }; let _device = run_output_device(params, { let mut clock = 0f32; move |data| { for samples in data.chunks_mut(params.channels_count) { clock = (clock + 1.0) % params.sample_rate as f32; let value = (clock * 440.0 * 2.0 * std::f32::consts::PI / params.sample_rate as f32).sin(); for sample in samples { *sample = value; } } } }) .unwrap(); std::thread::sleep(std::time::Duration::from_secs(5)); ``` -------------------------------- ### Initialize TinyAudio Output Device Source: https://github.com/mrdimas/tinyaudio/blob/main/README.md Demonstrates the basic initialization of an audio output device. This snippet shows how to set up the device parameters and provide a callback that outputs silence. Ensure the device is kept alive for the desired duration. ```rust use tinyaudio::prelude::*; let _device = run_output_device( OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }, move |_| { // Output silence }, ) .unwrap(); std::thread::sleep(std::time::Duration::from_secs(1)); ``` -------------------------------- ### Configure OutputDeviceParameters Source: https://context7.com/mrdimas/tinyaudio/llms.txt Define the audio format and buffer size for the output device. All three fields are required. The total number of f32 samples per callback is channels_count * channel_sample_count. ```rust use tinyaudio::prelude::*; let params = OutputDeviceParameters { // Stereo output channels_count: 2, // CD-quality sample rate sample_rate: 44100, // 100 ms of audio per callback invocation (44100 * 0.1 = 4410 samples per channel) channel_sample_count: 4410, }; // Total f32 samples per callback = channels_count * channel_sample_count = 2 * 4410 = 8820 ``` -------------------------------- ### Build Rust library for Xcode integration Source: https://github.com/mrdimas/tinyaudio/blob/main/ios-example/README.md Use this command within an Xcode Run Script phase to build the Rust library, making it compatible with Xcode projects. ```bash cargo lipo --xcode-integ --manifest-path $(PROJECT_DIR)../Rust-TinyAudioExample/Cargo.toml ``` -------------------------------- ### OutputDeviceParameters Source: https://context7.com/mrdimas/tinyaudio/llms.txt Defines the audio format and buffer sizing for the output device. All fields are required. ```APIDOC ## Struct: OutputDeviceParameters ### Description Represents the configuration for an audio output stream, including channel count, sample rate, and buffer size. ### Fields - **channels_count** (usize) - Required - The number of audio channels (e.g., 1 for mono, 2 for stereo). - **sample_rate** (u32) - Required - The number of samples per second (e.g., 44100 for CD quality). - **channel_sample_count** (usize) - Required - The number of samples per channel for each callback invocation. The total number of `f32` samples supplied to the callback on each call equals `channels_count * channel_sample_count`. ``` -------------------------------- ### Run tinyaudio on Android Source: https://github.com/mrdimas/tinyaudio/blob/main/android-examples/README.md Use this command to build and run the tinyaudio application on an Android device or emulator. Ensure your device is connected and recognized. ```bash cargo apk run --target=armv7-linux-androideabi ``` -------------------------------- ### WebAssembly Sine Wave Playback Source: https://context7.com/mrdimas/tinyaudio/llms.txt Plays a sine wave in WebAssembly. The audio device must be created within a user-initiated event handler due to browser autoplay policies. ```rust // src/lib.rs (compiled to WASM) use tinyaudio::prelude::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn play_sine_wave() -> OutputDevice { let params = OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }; run_output_device(params, { let mut clock = 0f32; move |data| { for samples in data.chunks_mut(params.channels_count) { clock = (clock + 1.0) % params.sample_rate as f32; let value = (clock * 440.0 * 2.0 * std::f32::consts::PI / params.sample_rate as f32).sin(); for sample in samples { *sample = value; } } } }) .unwrap() } ``` ```javascript // main.js — must be triggered by a user click, not on page load const play_sine_wave = import('./pkg/wasm_examples.js') .then(({ default: init, play_sine_wave }) => init().then(() => play_sine_wave)); document.querySelector('#button-start').addEventListener('click', async () => { const device = (await play_sine_wave)(); // Explicitly release Web Audio resources after 5 seconds setTimeout(() => device.close(), 5000); }, { once: true, passive: true }); ``` -------------------------------- ### iOS C FFI Audio Device Management Source: https://context7.com/mrdimas/tinyaudio/llms.txt Manages an audio device on iOS via a C FFI bridge. Functions are exposed for creating, checking initialization status, and destroying the audio device. ```rust // ios-example/Rust-TinyAudioExample/src/lib.rs use tinyaudio::prelude::*; static mut DEVICE_HANDLE: Option = None; #[no_mangle] pub extern "C" fn create_audio_device() -> i32 { let params = OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }; let result = run_output_device(params, { let mut clock = 0f32; move |data| { for samples in data.chunks_mut(params.channels_count) { clock = (clock + 1.0) % params.sample_rate as f32; let value = (clock * 440.0 * 2.0 * std::f32::consts::PI / params.sample_rate as f32).sin(); for sample in samples { *sample = value; } } } }); match result { Ok(device) => { unsafe { DEVICE_HANDLE = Some(device); } 1 } Err(_) => -1, } } #[no_mangle] pub extern "C" fn is_audio_initialized() -> i32 { unsafe { if DEVICE_HANDLE.is_some() { 1 } else { 0 } } } #[no_mangle] pub extern "C" fn destroy_audio_device() { unsafe { DEVICE_HANDLE = None; } // Drop releases all CoreAudio resources } ``` ```swift // Swift call site if create_audio_device() == 1 { print("Audio started") } else { print("Failed to start audio") } // Later: destroy_audio_device() ``` -------------------------------- ### Add TinyAudio to Cargo.toml Source: https://context7.com/mrdimas/tinyaudio/llms.txt Add the TinyAudio crate to your project's Cargo.toml file. On Linux, you can choose between the ALSA (default) or PulseAudio backend using features. ```toml # Default (ALSA on Linux) [dependencies] tinyaudio = "2" ``` ```toml # PulseAudio backend on Linux [dependencies] tinyaudio = { version = "2", default-features = false, features = ["pulse"] } ``` -------------------------------- ### Manage Audio Stream Lifetime with OutputDevice Source: https://context7.com/mrdimas/tinyaudio/llms.txt The `OutputDevice` handle returned by `run_output_device` manages the audio stream's lifetime. Audio plays while the handle is alive. Use `OutputDevice::close()` for explicit shutdown, especially in environments like WebAssembly where drop timing is uncertain. ```rust use tinyaudio::prelude::*; fn main() { let params = OutputDeviceParameters { channels_count: 1, // Mono sample_rate: 48000, channel_sample_count: 4800, }; let mut device = run_output_device(params, move |data| { // Fill with silence for sample in data.iter_mut() { *sample = 0.0; } }) .expect("Failed to open audio device"); std::thread::sleep(std::time::Duration::from_secs(2)); // Explicitly close the device and free system resources before dropping device.close(); // Any further calls to close() after the first are safe no-ops device.close(); } ``` -------------------------------- ### Android Native Activity Audio Playback Source: https://context7.com/mrdimas/tinyaudio/llms.txt Plays a sine wave on Android using the native activity. Audio initialization must occur after GainedFocus. ```rust use android_activity::{AndroidApp, MainEvent, PollEvent}; use tinyaudio::prelude::*; fn play_sine_wave() -> OutputDevice { let params = OutputDeviceParameters { channels_count: 2, sample_rate: 44100, channel_sample_count: 4410, }; run_output_device(params, { let mut clock = 0f32; move |data| { for samples in data.chunks_mut(params.channels_count) { clock = (clock + 1.0) % params.sample_rate as f32; let value = (clock * 440.0 * 2.0 * std::f32::consts::PI / params.sample_rate as f32).sin(); for sample in samples { *sample = value; } } } }) .unwrap() } #[no_mangle] fn android_main(app: AndroidApp) { let mut device = None; loop { app.poll_events(Some(std::time::Duration::from_millis(100)), |event| { match event { PollEvent::Main(MainEvent::GainedFocus) => { // IMPORTANT: only initialize audio after GainedFocus device = Some(play_sine_wave()); } PollEvent::Main(MainEvent::Destroy) => return, _ => {} } }); } } ``` -------------------------------- ### Remove built static library Source: https://github.com/mrdimas/tinyaudio/blob/main/ios-example/README.md This command, used in a subsequent Xcode Run Script phase, cleans up the built static library from the Rust project's target directory. ```bash rm -fv $(PROJECT_DIR)/../Rust-TinyAudioExample/target/universal/*/*.a ``` -------------------------------- ### OutputDevice::close Source: https://context7.com/mrdimas/tinyaudio/llms.txt Explicitly shuts down the audio stream and releases system resources associated with the OutputDevice. This is useful for deterministic cleanup, especially in environments like WebAssembly. ```APIDOC ## Method: OutputDevice::close ### Description Manually closes the audio output device, freeing associated system resources. Calling this method multiple times is safe and has no additional effect after the first call. ### Usage ```rust let mut device = tinyaudio::run_output_device(params, |data| { /* ... */ }).expect("Failed to open audio device"); // ... device.close(); // Explicitly shut down the device ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.