### Creating a Scraped Example for a Function Source: https://docs.rs/tinyaudio/2.0.0/scrape-examples-help.html This example demonstrates how to create a separate Rust file (`examples/ex.rs`) that calls a documented function from your crate. This call will be scraped and included in the documentation for `a_func`. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Run Output Device Example Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Plays a 440 Hz sine wave for 5 seconds using the default audio output device. Ensure the `run_output_device` function is available in scope. ```rust #[allow(clippy::needless_return)] pub fn run_output_device( params: OutputDeviceParameters, data_callback: C, ) -> Result> where C: FnMut(&mut [f32]) + Send + 'static, { #[cfg(target_os = "windows")] { return Ok(OutputDevice::new(directsound::DirectSoundDevice::new( params, data_callback, )?)); } #[cfg(target_os = "android")] { return Ok(OutputDevice::new(aaudio::AAudioOutputDevice::new( params, data_callback, )?)); } #[cfg(target_os = "linux")] { #[cfg(feature = "alsa")] { return Ok(OutputDevice::new(alsa::AlsaSoundDevice::new( params, data_callback, )?)); ``` ```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 Audio Output Device Source: https://docs.rs/tinyaudio/2.0.0/src/init/init.rs.html Initializes an audio output device with specified parameters and a callback for processing audio data. The example outputs silence and sleeps for a second to keep the device open. ```Rust use tinyaudio::prelude::*; fn main() { 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)); } ``` -------------------------------- ### Initialize ALSA Sound Device Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Initializes a new ALSA sound device for playback. This function configures hardware and software parameters, sets up the audio buffer, and starts a data sending thread. ```rust pub fn new(params: OutputDeviceParameters, data_callback: C) -> Result> where C: FnMut(&mut [f32]) + Send + 'static, Self: Sized, { unsafe { let name = CString::new("default").unwrap(); let frame_count = params.channel_sample_count; let mut playback_device = std::ptr::null_mut(); check(snd_pcm_open( &mut playback_device, name.as_ptr() as *const _, SND_PCM_STREAM_PLAYBACK, 0, ))?; let mut hw_params = std::ptr::null_mut(); check(snd_pcm_hw_params_malloc(&mut hw_params))?; check(snd_pcm_hw_params_any(playback_device, hw_params))?; let access = SND_PCM_ACCESS_RW_INTERLEAVED; check(snd_pcm_hw_params_set_access( playback_device, hw_params, access, ))?; check(snd_pcm_hw_params_set_format( playback_device, hw_params, SND_PCM_FORMAT_S16_LE, ))?; let mut exact_rate = params.sample_rate as ::std::os::raw::c_uint; check(snd_pcm_hw_params_set_rate_near( playback_device, hw_params, &mut exact_rate, std::ptr::null_mut(), ))?; check(snd_pcm_hw_params_set_channels( playback_device, hw_params, params.channels_count as ::std::os::raw::c_uint, ))?; let mut _exact_period = frame_count as snd_pcm_uframes_t; let mut _direction = 0; check(snd_pcm_hw_params_set_period_size_near( playback_device, hw_params, &mut _exact_period, &mut _direction, ))?; let mut exact_size = (frame_count * 2) as ::std::os::raw::c_ulong; check(snd_pcm_hw_params_set_buffer_size_near( playback_device, hw_params, &mut exact_size, ))?; check(snd_pcm_hw_params(playback_device, hw_params))?; snd_pcm_hw_params_free(hw_params); let mut sw_params = std::ptr::null_mut(); check(snd_pcm_sw_params_malloc(&mut sw_params))?; check(snd_pcm_sw_params_current(playback_device, sw_params))?; check(snd_pcm_sw_params_set_avail_min( playback_device, sw_params, frame_count as ::std::os::raw::c_ulong, ))?; check(snd_pcm_sw_params_set_start_threshold( playback_device, sw_params, frame_count as ::std::os::raw::c_ulong, ))?; check(snd_pcm_sw_params(playback_device, sw_params))?; check(snd_pcm_prepare(playback_device))?; let is_running = Arc::new(AtomicBool::new(true)); let thread_handle = DataSender { playback_device, callback: data_callback, data_buffer: vec![0.0f32; params.channel_sample_count * params.channels_count], output_buffer: vec![0i16; params.channel_sample_count * params.channels_count], is_running: is_running.clone(), params, } .run_in_thread()?; Ok(Self { playback_device, is_running, thread_handle: Some(thread_handle), }) } } ``` -------------------------------- ### Type ID Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Gets the `TypeId` of the `OutputDevice`. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Initialize TinyAudio Output Device Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/index.html Demonstrates the basic initialization of an audio output device. This snippet plays silence and is useful for setting up the audio context. ```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)); ``` -------------------------------- ### run_output_device Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Creates a new output device using the operating system's default audio output. It plays samples generated by the provided `data_callback`, which is invoked periodically to produce audio data. ```APIDOC /// Creates a new output device that uses default audio output device of your operating system to play the /// samples produced by the specified `data_callback`. The callback will be called periodically to generate /// another portion of samples. /// /// ## Examples /// /// The following examples plays a 440 Hz sine wave for 5 seconds. /// /// ```rust,no_run /// # 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)); /// ``` #[allow(clippy::needless_return)] pub fn run_output_device( params: OutputDeviceParameters, data_callback: C, ) -> Result> where C: FnMut(&mut [f32]) + Send + 'static, { ``` -------------------------------- ### Play Sine Wave with tinyaudio Source: https://docs.rs/tinyaudio/2.0.0/src/sine/sine.rs.html Initializes a default sound output device and plays a sine wave. Ensure the tinyaudio crate is added as a dependency. ```rust use tinyaudio::prelude::*; fn main() { 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)); } ``` -------------------------------- ### run_output_device Function Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/fn.run_output_device.html Creates a new output device using the system's default audio output. It takes output device parameters and a mutable closure that will be called to generate audio samples. ```APIDOC ## Function run_output_device ### Description Creates a new output device that uses default audio output device of your operating system to play the samples produced by the specified `data_callback`. The callback will be called periodically to generate another portion of samples. ### Signature ```rust pub fn run_output_device( params: OutputDeviceParameters, data_callback: C, ) -> Result> where C: FnMut(&mut [f32]) + Send + 'static, ``` ### Parameters * `params` (OutputDeviceParameters): Configuration for the output device, including channel count, sample rate, and sample count per channel. * `data_callback` (C): A mutable closure that takes a mutable slice of f32 samples and is responsible for filling it with audio data. It must be `Send` and have a `'static` lifetime. ### Returns * `Result>`: Returns an `OutputDevice` on success, which can be used to manage the audio playback. Returns an error if the device cannot be created or managed. ### Examples #### Playing a 440 Hz sine wave for 5 seconds ```rust 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)); ``` #### Basic example with silence ```rust 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)); ``` ``` -------------------------------- ### CloneToUninit Method (Experimental) Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Performs copy-assignment from self to an uninitialized destination. This is a nightly-only experimental API. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Initialize output device with silence Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/fn.run_output_device.html Initializes an output device that produces silence. A short sleep is included to keep the device open for a brief period. ```rust 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)); ``` -------------------------------- ### WebAssembly Audio Output Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Initializes a Web Audio API device for audio output when targeting WebAssembly. This is the standard approach for web-based audio. ```rust #[cfg(all(target_os = "unknown", target_arch = "wasm32"))] { return Ok(OutputDevice::new(web::WebAudioDevice::new( params, data_callback, )?)); } ``` -------------------------------- ### OutputDeviceParameters Structure Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Defines the configuration for an audio output device, including sample rate, channel count, and buffer size. ```rust /// Parameters of an output device. #[derive(Copy, Clone)] pub struct OutputDeviceParameters { /// Sample rate of your audio data. Typical values are: 11025 Hz, 22050 Hz, 44100 Hz (default), 48000 Hz, /// 96000 Hz. pub sample_rate: usize, /// Desired amount of audio channels. Must be at least one. Typical values: 1 - mono, 2 - stereo, etc. /// The data provided by the call back is _interleaved_, which means that if you have two channels then /// the sample layout will be like so: `LRLRLR..`, where `L` - a sample of left channel, and `R` a sample /// of right channel. pub channels_count: usize, /// Amount of samples per each channel. Allows you to tweak audio latency, the more the value the more /// latency will be and vice versa. Keep in mind, that your data callback must be able to render the /// samples while previous portion of data is being played, otherwise you'll get a glitchy audio. /// /// If you need to get a specific length in **seconds**, then you need to use sampling rate to calculate /// the required amount of samples per channel: `channel_sample_count = sample_rate * time_in_seconds`. /// /// The crate guarantees, that the intermediate buffer size will match the requested value. pub channel_sample_count: usize, } ``` -------------------------------- ### macOS/iOS Core Audio Output Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Initializes a Core Audio device for audio output on macOS and iOS. This is the native audio framework for Apple platforms. ```rust #[cfg(any(target_os = "macos", target_os = "ios"))] { return Ok(OutputDevice::new(coreaudio::CoreaudioSoundDevice::new( params, data_callback, )?)); } ``` -------------------------------- ### Play a 440 Hz sine wave for 5 seconds Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/fn.run_output_device.html Configures and runs an output device to play a sine wave. The callback generates audio samples for a 440 Hz tone. Requires a 5-second sleep to allow playback. ```rust 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)); ``` -------------------------------- ### Run DataSender in a New Thread Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Spawns a new thread to run the `run_send_loop` method of the DataSender. This allows audio data to be processed and sent to the ALSA device asynchronously. ```rust pub fn run_in_thread(mut self) -> Result, Box> { Ok(std::thread::Builder::new() .name("AlsaDataSender".to_string()) .spawn(move || self.run_send_loop())?) } ``` -------------------------------- ### OutputDeviceParameters Struct Definition Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Defines the parameters for an audio output device. Configure sample rate, channel count, and channel sample count to manage audio output and latency. ```rust pub struct OutputDeviceParameters { pub sample_rate: usize, pub channels_count: usize, pub channel_sample_count: usize, } ``` -------------------------------- ### OutputDeviceParameters Struct Definition Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Defines the parameters for an audio output device. ```APIDOC ## Struct OutputDeviceParameters ### Description Parameters of an output device. ### Fields - `sample_rate: usize` - Sample rate of your audio data. Typical values are: 11025 Hz, 22050 Hz, 44100 Hz (default), 48000 Hz, 96000 Hz. - `channels_count: usize` - Desired amount of audio channels. Must be at least one. Typical values: 1 - mono, 2 - stereo, etc. The data provided by the call back is _interleaved_ , which means that if you have two channels then the sample layout will be like so: `LRLRLR..`, where `L` - a sample of left channel, and `R` a sample of right channel. - `channel_sample_count: usize` - Amount of samples per each channel. Allows you to tweak audio latency, the more the value the more latency will be and vice versa. Keep in mind, that your data callback must be able to render the samples while previous portion of data is being played, otherwise you’ll get a glitchy audio. If you need to get a specific length in **seconds** , then you need to use sampling rate to calculate the required amount of samples per channel: `channel_sample_count = sample_rate * time_in_seconds`. The crate guarantees, that the intermediate buffer size will match the requested value. ``` -------------------------------- ### Clone Implementation for OutputDeviceParameters Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Provides a method to create a duplicate of the OutputDeviceParameters value. ```rust fn clone(&self) -> OutputDeviceParameters ``` -------------------------------- ### CloneFrom Implementation for OutputDeviceParameters Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Enables copying assignment from one OutputDeviceParameters instance to another. ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Documenting a Function with Rustdoc Source: https://docs.rs/tinyaudio/2.0.0/scrape-examples-help.html This shows a public function in `src/lib.rs` that can be documented by Rustdoc. Ensure your function is public to be documented. ```rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### Unsupported Platform Error Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Returns an error indicating that the current platform is not supported by the tinyaudio library. This handles cases not explicitly covered by other platform configurations. ```rust #[cfg(not(any( target_os = "windows", target_os = "linux", target_os = "android", target_os = "macos", target_os = "ios", all(target_os = "unknown", target_arch = "wasm32") )))] { Err("Platform is not supported".to_string().into()) } ``` -------------------------------- ### Borrow Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Immutably borrows the `OutputDevice`. This is part of the `Borrow` trait implementation. ```rust fn borrow(&self) -> &T ``` -------------------------------- ### ALSA Data Sending Loop Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Continuously processes audio data, converts it from f32 to i16, and writes it to the ALSA playback device. Includes a loop for attempting to recover from write errors. ```rust pub fn run_send_loop(&mut self) { while self.is_running.load(Ordering::SeqCst) { (self.callback)(&mut self.data_buffer); debug_assert_eq!(self.data_buffer.len(), self.output_buffer.len()); for (in_sample, out_sample) in self.data_buffer.iter().zip(self.output_buffer.iter_mut()) { *out_sample = (*in_sample * i16::MAX as f32) as i16; } 'try_loop: for _ in 0..10 { unsafe { let err = snd_pcm_writei( self.playback_device, self.output_buffer.as_ptr() as *const _, self.params.channel_sample_count as ::std::os::raw::c_ulong, ) as i32; if err < 0 { // Try to recover from any errors and re-send data. snd_pcm_recover(self.playback_device, err, 1); } else { break 'try_loop; } } } } } ``` -------------------------------- ### Linux PulseAudio Output Device Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html Selects PulseAudio for audio output on Linux when the 'pulse' feature is enabled and 'alsa' is not. Requires a PulseAudio server to be running. ```rust #[cfg(all(feature = "pulse", not(feature = "alsa")))] { return Ok(OutputDevice::new(pulse::PulseSoundDevice::new( params, data_callback, )?)); } ``` -------------------------------- ### Linux Feature Selection Error Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/lib.rs.html This compile-time error is triggered on Linux if neither the 'alsa' nor 'pulse' feature is selected, ensuring a valid audio backend is chosen. ```rust #[cfg(all(not(feature = "alsa"), not(feature = "pulse")))] { compile_error!("Select \"alsa\" or \"pulse\" feature to use an audio device on Linux") } ``` -------------------------------- ### From Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Returns the argument unchanged. This is part of the `From` trait implementation. ```rust fn from(t: T) -> T ``` -------------------------------- ### OutputDevice Struct Definition Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Defines the OutputDevice struct, which is an opaque handle to an audio output device. Its fields are private. ```rust pub struct OutputDevice { /* private fields */ } ``` -------------------------------- ### Into Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Calls `U::from(self)` to perform a conversion. This is part of the `Into` trait implementation. ```rust fn into(self) -> U ``` -------------------------------- ### TryInto Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Performs a conversion that may fail. The `Error` type is determined by the `TryFrom` implementation. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### BorrowMut Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Mutably borrows the `OutputDevice`. This is part of the `BorrowMut` trait implementation. ```rust fn borrow_mut(&mut self) -> &mut T ``` -------------------------------- ### TryFrom Implementation Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Performs a conversion that may fail. The `Error` type is `Infallible`. ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Implement Drop for AlsaSoundDevice Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Ensures the ALSA device is properly closed and the associated thread is joined when the AlsaSoundDevice goes out of scope. This prevents resource leaks and ensures orderly shutdown. ```rust impl Drop for AlsaSoundDevice { fn drop(&mut self) { self.is_running.store(false, Ordering::SeqCst); self.thread_handle .take() .expect("Alsa thread must exist!") .join() .unwrap(); unsafe { snd_pcm_close(self.playback_device); } } } ``` -------------------------------- ### Close Output Device Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Closes the output device and releases all system resources. Subsequent calls to this method have no effect. ```rust pub fn close(&mut self) ``` -------------------------------- ### OutputDevice::close Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDevice.html Closes the output device and releases all system resources occupied by it. Subsequent calls to this method after the device has been closed will have no effect. ```APIDOC ## pub fn close(&mut self) ### Description Closes the output device and release all system resources occupied by it. Any calls of this method after the device was closed does nothing. ### Method `close` ### Parameters - `&mut self`: A mutable reference to the `OutputDevice` instance. ``` -------------------------------- ### CloneInto Method for Generic Types Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Uses borrowed data to replace owned data, typically by cloning. ```rust fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Convert ALSA Error Code to String Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Converts an ALSA error code into a human-readable string. This is useful for debugging and providing informative error messages. ```rust pub fn err_code_to_string(err_code: c_int) -> String { unsafe { let message = CStr::from_ptr(snd_strerror(err_code) as *const _) .to_bytes() .to_vec(); String::from_utf8(message).unwrap() } } ``` -------------------------------- ### Check ALSA Operation Result Source: https://docs.rs/tinyaudio/2.0.0/src/tinyaudio/alsa.rs.html Checks the return code of an ALSA operation. If the code indicates an error (less than 0), it returns a boxed error containing the string representation of the error. ```rust pub fn check(err_code: c_int) -> Result<(), Box> { if err_code < 0 { Err(err_code_to_string(err_code).into()) } else { Ok(()) } } ``` -------------------------------- ### ToOwned Method for Generic Types Source: https://docs.rs/tinyaudio/2.0.0/tinyaudio/struct.OutputDeviceParameters.html Creates owned data from borrowed data, typically by cloning. ```rust fn to_owned(&self) -> T ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.