Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Play An Audio File To Loopback With Rust

This plays a sound from a rust app to a sounds interface from Mac's loopback app. I use this to send stuff to OBS when I'm streaming

This works, but is really just a prototype to play with to prove the concept

Code

```cargo
[dependencies]
cpal = "0.15"
rodio = "0.17"
```

use std::fs::File;
use std::io::BufReader;
use rodio::{Decoder, OutputStream, Sink};
use cpal::traits::HostTrait;
use cpal::traits::DeviceTrait;

fn main() { 

  let host = cpal::default_host();
  if let Ok(output_devices) = host.input_devices() {
    output_devices.for_each(|d| {
      if let Ok(name) = d.name() {
        if name == "LoopbackTesting".to_string() {
          println!("{}", name);
          let (_stream, stream_handle) = OutputStream::try_from_device(&d).unwrap();
          let file = BufReader::new(File::open("audio/hydrate.mp3").unwrap());
          let sink = Sink::try_new(&stream_handle).unwrap();
          let source = Decoder::new(file).unwrap();
          sink.append(source);
          sink.sleep_until_end();
        }
      }
    });
  }

}

Results

LoopbackTesting
  • See if this can be done without cpal (since it's what's used under the hood there might be a direct way to use it)

References