Host

Struct Host 

Source
pub struct Host { /* private fields */ }
Expand description

An RtAudio Host instance. This is used to enumerate audio devices before opening a stream.

Implementations§

Source§

impl Host

Source

pub fn new(api: Api) -> Result<Self, RtAudioError>

Create a new RtAudio Host with the given API. This host is used to enumerate audio devices before opening a stream.

If Api::Unspecified is used, then the best one for the system will automatically be chosen.

Examples found in repository?
examples/enumerate.rs (line 7)
1fn main() {
2    dbg!(rtaudio::version());
3
4    for api in rtaudio::compiled_apis() {
5        dbg!(api.get_display_name());
6
7        match rtaudio::Host::new(api) {
8            Ok(rt) => {
9                for device_info in rt.iter_devices() {
10                    dbg!(device_info);
11                }
12            }
13            Err(e) => {
14                eprintln!("{}", e);
15            }
16        }
17
18        println!("---------------------------------------------");
19    }
20}
More examples
Hide additional examples
examples/loopback.rs (line 4)
3fn main() {
4    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
5    dbg!(host.api());
6
7    let out_device = host.default_output_device().unwrap();
8    let in_device = host.default_input_device().unwrap();
9
10    let mut stream_handle = host
11        .open_stream(
12            Some(DeviceParams {
13                device_id: out_device.id,
14                num_channels: 2,
15                first_channel: 0,
16            }),
17            Some(DeviceParams {
18                device_id: in_device.id,
19                num_channels: 2,
20                first_channel: 0,
21            }),
22            SampleFormat::Float32,
23            out_device.preferred_sample_rate,
24            256,
25            StreamOptions::default(),
26            |error| eprintln!("{}", error),
27        )
28        .unwrap();
29    dbg!(stream_handle.info());
30
31    stream_handle
32        .start(
33            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
34                if let Buffers::Float32 { output, input } = buffers {
35                    // Copy the input to the output.
36                    output.copy_from_slice(input);
37                }
38            },
39        )
40        .unwrap();
41
42    // Wait 3 seconds before closing.
43    std::thread::sleep(std::time::Duration::from_millis(3000));
44}
examples/playback_sine.rs (line 7)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    dbg!(host.api());
9
10    let out_device = host.default_output_device().unwrap();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            |error| eprintln!("{}", error),
25        )
26        .unwrap();
27    dbg!(stream_handle.info());
28
29    let mut phasor = 0.0;
30    let phasor_inc = FREQ_HZ / stream_handle.info().sample_rate as f32;
31
32    stream_handle
33        .start(
34            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
35                if let Buffers::Float32 { output, input: _ } = buffers {
36                    // By default, buffers are interleaved.
37                    for frame in output.chunks_mut(2) {
38                        // Generate a sine wave at 440 Hz at 50% volume.
39                        let val = (phasor * std::f32::consts::TAU).sin() * AMPLITUDE;
40                        phasor = (phasor + phasor_inc).fract();
41
42                        frame[0] = val;
43                        frame[1] = val;
44                    }
45                }
46            },
47        )
48        .unwrap();
49
50    // Wait 3 seconds before closing.
51    std::thread::sleep(std::time::Duration::from_millis(3000));
52}
examples/handle_error.rs (line 7)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    let out_device = host.default_output_device().unwrap();
9
10    let (error_tx, error_rx) = std::sync::mpsc::channel();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            move |error| error_tx.send(error).unwrap(),
25        )
26        .unwrap();
27
28    stream_handle
29        .start(
30            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
31                if let Buffers::Float32 { output, input: _ } = buffers {
32                    // Fill the output with silence.
33                    output.fill(0.0);
34                }
35            },
36        )
37        .unwrap();
38
39    // Play for 5 seconds and then close.
40    let t = Instant::now();
41    while t.elapsed() < Duration::from_secs(5) {
42        // Periodically poll to see if an error has happened.
43        if let Ok(error) = error_rx.try_recv() {
44            // An error occured that caused the stream to close (for example a
45            // device was unplugged). Now our stream_handle object should be
46            // manually closed or dropped.
47            eprintln!("{}", error);
48
49            break;
50        }
51
52        std::thread::sleep(Duration::from_millis(16));
53    }
54}
Source

pub fn show_warnings(&self, show: bool)

Whether or not to print extra warnings to the terminal output.

By default this is set to false.

Source

pub fn api(&self) -> Api

The API being used by this instance.

Examples found in repository?
examples/loopback.rs (line 5)
3fn main() {
4    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
5    dbg!(host.api());
6
7    let out_device = host.default_output_device().unwrap();
8    let in_device = host.default_input_device().unwrap();
9
10    let mut stream_handle = host
11        .open_stream(
12            Some(DeviceParams {
13                device_id: out_device.id,
14                num_channels: 2,
15                first_channel: 0,
16            }),
17            Some(DeviceParams {
18                device_id: in_device.id,
19                num_channels: 2,
20                first_channel: 0,
21            }),
22            SampleFormat::Float32,
23            out_device.preferred_sample_rate,
24            256,
25            StreamOptions::default(),
26            |error| eprintln!("{}", error),
27        )
28        .unwrap();
29    dbg!(stream_handle.info());
30
31    stream_handle
32        .start(
33            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
34                if let Buffers::Float32 { output, input } = buffers {
35                    // Copy the input to the output.
36                    output.copy_from_slice(input);
37                }
38            },
39        )
40        .unwrap();
41
42    // Wait 3 seconds before closing.
43    std::thread::sleep(std::time::Duration::from_millis(3000));
44}
More examples
Hide additional examples
examples/playback_sine.rs (line 8)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    dbg!(host.api());
9
10    let out_device = host.default_output_device().unwrap();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            |error| eprintln!("{}", error),
25        )
26        .unwrap();
27    dbg!(stream_handle.info());
28
29    let mut phasor = 0.0;
30    let phasor_inc = FREQ_HZ / stream_handle.info().sample_rate as f32;
31
32    stream_handle
33        .start(
34            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
35                if let Buffers::Float32 { output, input: _ } = buffers {
36                    // By default, buffers are interleaved.
37                    for frame in output.chunks_mut(2) {
38                        // Generate a sine wave at 440 Hz at 50% volume.
39                        let val = (phasor * std::f32::consts::TAU).sin() * AMPLITUDE;
40                        phasor = (phasor + phasor_inc).fract();
41
42                        frame[0] = val;
43                        frame[1] = val;
44                    }
45                }
46            },
47        )
48        .unwrap();
49
50    // Wait 3 seconds before closing.
51    std::thread::sleep(std::time::Duration::from_millis(3000));
52}
Source

pub fn num_devices(&self) -> usize

Retrieve the number of available audio devices.

Source

pub fn get_device_info_by_index( &self, index: usize, ) -> Result<DeviceInfo, RtAudioError>

Retrieve information about an audio device by its index.

Source

pub fn get_device_info_by_id( &self, id: DeviceID, ) -> Result<DeviceInfo, RtAudioError>

Retrieve info about an audio device by its ID.

Source

pub fn iter_devices_complete<'a>(&'a self) -> DeviceIter<'a>

Retrieve an iterator over all the available audio devices (including ones that have failed to scan properly).

Source

pub fn iter_devices<'a>(&'a self) -> impl Iterator<Item = DeviceInfo> + 'a

Retrieve an iterator over the available audio devices.

If there was a problem scanning a device, a warning will be printed to the log.

Examples found in repository?
examples/enumerate.rs (line 9)
1fn main() {
2    dbg!(rtaudio::version());
3
4    for api in rtaudio::compiled_apis() {
5        dbg!(api.get_display_name());
6
7        match rtaudio::Host::new(api) {
8            Ok(rt) => {
9                for device_info in rt.iter_devices() {
10                    dbg!(device_info);
11                }
12            }
13            Err(e) => {
14                eprintln!("{}", e);
15            }
16        }
17
18        println!("---------------------------------------------");
19    }
20}
Source

pub fn iter_output_devices<'a>( &'a self, ) -> impl Iterator<Item = DeviceInfo> + 'a

Retrieve an iterator over the available output audio devices.

If there was a problem scanning a device, a warning will be printed to the log.

Source

pub fn iter_input_devices<'a>(&'a self) -> impl Iterator<Item = DeviceInfo> + 'a

Retrieve an iterator over the available input audio devices.

If there was a problem scanning a device, a warning will be printed to the log.

Source

pub fn iter_duplex_devices<'a>( &'a self, ) -> impl Iterator<Item = DeviceInfo> + 'a

Retrieve an iterator over the available duplex audio devices.

If there was a problem scanning a device, a warning will be printed to the log.

Source

pub fn default_output_device_id(&self) -> Option<DeviceID>

Returns the device ID (not index) of the default output device.

Source

pub fn default_input_device_id(&self) -> Option<DeviceID>

Returns the device ID (not index) of the default input device.

Source

pub fn default_output_device(&self) -> Result<DeviceInfo, RtAudioError>

Returns information about the default output device.

Examples found in repository?
examples/loopback.rs (line 7)
3fn main() {
4    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
5    dbg!(host.api());
6
7    let out_device = host.default_output_device().unwrap();
8    let in_device = host.default_input_device().unwrap();
9
10    let mut stream_handle = host
11        .open_stream(
12            Some(DeviceParams {
13                device_id: out_device.id,
14                num_channels: 2,
15                first_channel: 0,
16            }),
17            Some(DeviceParams {
18                device_id: in_device.id,
19                num_channels: 2,
20                first_channel: 0,
21            }),
22            SampleFormat::Float32,
23            out_device.preferred_sample_rate,
24            256,
25            StreamOptions::default(),
26            |error| eprintln!("{}", error),
27        )
28        .unwrap();
29    dbg!(stream_handle.info());
30
31    stream_handle
32        .start(
33            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
34                if let Buffers::Float32 { output, input } = buffers {
35                    // Copy the input to the output.
36                    output.copy_from_slice(input);
37                }
38            },
39        )
40        .unwrap();
41
42    // Wait 3 seconds before closing.
43    std::thread::sleep(std::time::Duration::from_millis(3000));
44}
More examples
Hide additional examples
examples/playback_sine.rs (line 10)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    dbg!(host.api());
9
10    let out_device = host.default_output_device().unwrap();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            |error| eprintln!("{}", error),
25        )
26        .unwrap();
27    dbg!(stream_handle.info());
28
29    let mut phasor = 0.0;
30    let phasor_inc = FREQ_HZ / stream_handle.info().sample_rate as f32;
31
32    stream_handle
33        .start(
34            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
35                if let Buffers::Float32 { output, input: _ } = buffers {
36                    // By default, buffers are interleaved.
37                    for frame in output.chunks_mut(2) {
38                        // Generate a sine wave at 440 Hz at 50% volume.
39                        let val = (phasor * std::f32::consts::TAU).sin() * AMPLITUDE;
40                        phasor = (phasor + phasor_inc).fract();
41
42                        frame[0] = val;
43                        frame[1] = val;
44                    }
45                }
46            },
47        )
48        .unwrap();
49
50    // Wait 3 seconds before closing.
51    std::thread::sleep(std::time::Duration::from_millis(3000));
52}
examples/handle_error.rs (line 8)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    let out_device = host.default_output_device().unwrap();
9
10    let (error_tx, error_rx) = std::sync::mpsc::channel();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            move |error| error_tx.send(error).unwrap(),
25        )
26        .unwrap();
27
28    stream_handle
29        .start(
30            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
31                if let Buffers::Float32 { output, input: _ } = buffers {
32                    // Fill the output with silence.
33                    output.fill(0.0);
34                }
35            },
36        )
37        .unwrap();
38
39    // Play for 5 seconds and then close.
40    let t = Instant::now();
41    while t.elapsed() < Duration::from_secs(5) {
42        // Periodically poll to see if an error has happened.
43        if let Ok(error) = error_rx.try_recv() {
44            // An error occured that caused the stream to close (for example a
45            // device was unplugged). Now our stream_handle object should be
46            // manually closed or dropped.
47            eprintln!("{}", error);
48
49            break;
50        }
51
52        std::thread::sleep(Duration::from_millis(16));
53    }
54}
Source

pub fn default_input_device(&self) -> Result<DeviceInfo, RtAudioError>

Returns information about the default input device.

Examples found in repository?
examples/loopback.rs (line 8)
3fn main() {
4    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
5    dbg!(host.api());
6
7    let out_device = host.default_output_device().unwrap();
8    let in_device = host.default_input_device().unwrap();
9
10    let mut stream_handle = host
11        .open_stream(
12            Some(DeviceParams {
13                device_id: out_device.id,
14                num_channels: 2,
15                first_channel: 0,
16            }),
17            Some(DeviceParams {
18                device_id: in_device.id,
19                num_channels: 2,
20                first_channel: 0,
21            }),
22            SampleFormat::Float32,
23            out_device.preferred_sample_rate,
24            256,
25            StreamOptions::default(),
26            |error| eprintln!("{}", error),
27        )
28        .unwrap();
29    dbg!(stream_handle.info());
30
31    stream_handle
32        .start(
33            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
34                if let Buffers::Float32 { output, input } = buffers {
35                    // Copy the input to the output.
36                    output.copy_from_slice(input);
37                }
38            },
39        )
40        .unwrap();
41
42    // Wait 3 seconds before closing.
43    std::thread::sleep(std::time::Duration::from_millis(3000));
44}
Source

pub fn open_stream<E>( self, output_device: Option<DeviceParams>, input_device: Option<DeviceParams>, sample_format: SampleFormat, sample_rate: u32, buffer_frames: u32, options: StreamOptions, error_callback: E, ) -> Result<StreamHandle, (Self, RtAudioError)>
where E: FnOnce(RtAudioError) + Send + 'static,

Open a new audio stream.

  • output_device - The parameters for the output device to use. If you do not wish to use an output device, set this to None.
  • input_device - The parameters for the input device to use. If you do not wish to use an input device, set this to None.
  • sample_format - The sample format to use. If the device doesn’t natively support the given format, then it will automatically be converted to/from that format.
  • sample_rate - The sample rate to use. The stream may decide to use a different sample rate if it’s not supported.
  • buffer_frames - The desired maximum number of frames that can appear in a single process call. The stream may decide to use a different value if it’s not supported. The given value should be a power of 2.
  • options - Additional options for the stream.
  • error_callback - This will be called if there was an error that caused the stream to close. If this happens, the returned Stream struct should be manually closed or dropped.

Only one stream can be opened at a time (this is a limitation with RtAudio).

Examples found in repository?
examples/loopback.rs (lines 11-27)
3fn main() {
4    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
5    dbg!(host.api());
6
7    let out_device = host.default_output_device().unwrap();
8    let in_device = host.default_input_device().unwrap();
9
10    let mut stream_handle = host
11        .open_stream(
12            Some(DeviceParams {
13                device_id: out_device.id,
14                num_channels: 2,
15                first_channel: 0,
16            }),
17            Some(DeviceParams {
18                device_id: in_device.id,
19                num_channels: 2,
20                first_channel: 0,
21            }),
22            SampleFormat::Float32,
23            out_device.preferred_sample_rate,
24            256,
25            StreamOptions::default(),
26            |error| eprintln!("{}", error),
27        )
28        .unwrap();
29    dbg!(stream_handle.info());
30
31    stream_handle
32        .start(
33            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
34                if let Buffers::Float32 { output, input } = buffers {
35                    // Copy the input to the output.
36                    output.copy_from_slice(input);
37                }
38            },
39        )
40        .unwrap();
41
42    // Wait 3 seconds before closing.
43    std::thread::sleep(std::time::Duration::from_millis(3000));
44}
More examples
Hide additional examples
examples/playback_sine.rs (lines 13-25)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    dbg!(host.api());
9
10    let out_device = host.default_output_device().unwrap();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            |error| eprintln!("{}", error),
25        )
26        .unwrap();
27    dbg!(stream_handle.info());
28
29    let mut phasor = 0.0;
30    let phasor_inc = FREQ_HZ / stream_handle.info().sample_rate as f32;
31
32    stream_handle
33        .start(
34            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
35                if let Buffers::Float32 { output, input: _ } = buffers {
36                    // By default, buffers are interleaved.
37                    for frame in output.chunks_mut(2) {
38                        // Generate a sine wave at 440 Hz at 50% volume.
39                        let val = (phasor * std::f32::consts::TAU).sin() * AMPLITUDE;
40                        phasor = (phasor + phasor_inc).fract();
41
42                        frame[0] = val;
43                        frame[1] = val;
44                    }
45                }
46            },
47        )
48        .unwrap();
49
50    // Wait 3 seconds before closing.
51    std::thread::sleep(std::time::Duration::from_millis(3000));
52}
examples/handle_error.rs (lines 13-25)
6fn main() {
7    let host = rtaudio::Host::new(Api::Unspecified).unwrap();
8    let out_device = host.default_output_device().unwrap();
9
10    let (error_tx, error_rx) = std::sync::mpsc::channel();
11
12    let mut stream_handle = host
13        .open_stream(
14            Some(DeviceParams {
15                device_id: out_device.id,
16                num_channels: 2,
17                first_channel: 0,
18            }),
19            None,
20            SampleFormat::Float32,
21            out_device.preferred_sample_rate,
22            256,
23            StreamOptions::default(),
24            move |error| error_tx.send(error).unwrap(),
25        )
26        .unwrap();
27
28    stream_handle
29        .start(
30            move |buffers: Buffers<'_>, _info: &StreamInfo, _status: StreamStatus| {
31                if let Buffers::Float32 { output, input: _ } = buffers {
32                    // Fill the output with silence.
33                    output.fill(0.0);
34                }
35            },
36        )
37        .unwrap();
38
39    // Play for 5 seconds and then close.
40    let t = Instant::now();
41    while t.elapsed() < Duration::from_secs(5) {
42        // Periodically poll to see if an error has happened.
43        if let Ok(error) = error_rx.try_recv() {
44            // An error occured that caused the stream to close (for example a
45            // device was unplugged). Now our stream_handle object should be
46            // manually closed or dropped.
47            eprintln!("{}", error);
48
49            break;
50        }
51
52        std::thread::sleep(Duration::from_millis(16));
53    }
54}

Trait Implementations§

Source§

impl Debug for Host

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Host

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Host

§

impl RefUnwindSafe for Host

§

impl !Send for Host

§

impl !Sync for Host

§

impl Unpin for Host

§

impl UnwindSafe for Host

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.