Skip to main content

AudioStream

Struct AudioStream 

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

Audio output that is playing: an audio thread, and the device it fills.

Dropping it stops the thread and closes the device; what the device had not played yet is dropped. The drop waits for the thread up to 2 s, which it takes only when the system holds the device, as while it resumes from a suspend; past that, the thread is left to end with the process.

It is Send and Sync on every system.

Implementations§

Source§

impl AudioStream

Source

pub fn latency(&self) -> Option<Duration>

How long a sample waits in the device’s buffer before it is heard, as the device took it the last time it opened, besides what a sound server adds. None while there is no device: before the first one opens, and from the loss of one until it opens again.

Examples found in repository?
examples/audio.rs (line 103)
67fn run(mut args: Args, out: &mut dyn Write) -> Result<(), Box<dyn Error>> {
68    let seconds: f64 = args.parsed("--seconds")?.unwrap_or(10.0);
69    let volume: f32 = args.parsed("--volume")?.unwrap_or(0.2);
70    let latency_ms: u32 = args.parsed("--latency")?.unwrap_or(30);
71    if let Some(extra) = args.finish()?.first() {
72        return Err(format!("unexpected argument `{extra}`").into());
73    }
74    if !(0.0..=1.0).contains(&volume) {
75        return Err(format!("the volume {volume} is not from 0 to 1").into());
76    }
77    let length = Duration::try_from_secs_f64(seconds)?;
78
79    let periods = Arc::new(AtomicU64::new(0));
80    let underruns = Arc::new(AtomicU64::new(0));
81    let beeps = Beeps {
82        frame: 0,
83        volume,
84        periods: Arc::clone(&periods),
85        underruns: Arc::clone(&underruns),
86    };
87    let config = AudioOutputConfig {
88        latency_ms,
89        ..AudioOutputConfig::default()
90    };
91    let stream = open_audio(&config, Box::new(beeps))?;
92    writeln!(
93        out,
94        "audio: {} Hz, {} channels; beeps of 440 Hz on the left, then 660 Hz on the right",
95        config.sample_rate, config.channels,
96    )?;
97
98    let start = Instant::now();
99    let mut second = 1;
100    while start.elapsed() < length {
101        let next = start + Duration::from_secs(second);
102        thread::sleep(next.saturating_duration_since(Instant::now()).min(length));
103        let device = match stream.latency() {
104            Some(latency) => format!("{:.1} ms of latency", latency.as_secs_f64() * 1000.0),
105            None => "no device".to_string(),
106        };
107        writeln!(
108            out,
109            "{:6.1} s: {} periods, {} underruns, {device}",
110            start.elapsed().as_secs_f64(),
111            periods.load(Ordering::Relaxed),
112            underruns.load(Ordering::Relaxed),
113        )?;
114        second += 1;
115    }
116    // The stream stops as it drops, here.
117    Ok(())
118}

Auto Trait Implementations§

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.