commit
36ae2f02a8
7 changed files with 306 additions and 58 deletions
4
.github/workflows/cpal.yml
vendored
4
.github/workflows/cpal.yml
vendored
|
|
@ -262,6 +262,8 @@ jobs:
|
|||
toolchain: stable
|
||||
override: true
|
||||
target: armv7-linux-androideabi
|
||||
- name: Check android
|
||||
run: cargo check --example android --target armv7-linux-androideabi --verbose
|
||||
- name: Check beep
|
||||
run: cargo check --example beep --target armv7-linux-androideabi --verbose
|
||||
- name: Check enumerate
|
||||
|
|
@ -284,4 +286,4 @@ jobs:
|
|||
- name: Install Cargo APK
|
||||
run: cargo install cargo-apk
|
||||
- name: Build APK
|
||||
run: cargo apk build --example beep
|
||||
run: cargo apk build --example android
|
||||
|
|
|
|||
14
Cargo.toml
14
Cargo.toml
|
|
@ -18,6 +18,7 @@ thiserror = "1.0.2"
|
|||
anyhow = "1.0.12"
|
||||
hound = "3.4"
|
||||
ringbuf = "0.2"
|
||||
clap = { version = "2.33.3", default-features = false }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winapi = { version = "0.3", features = ["audiosessiontypes", "audioclient", "coml2api", "combaseapi", "debug", "devpkey", "handleapi", "ksmedia", "mmdeviceapi", "objbase", "profileapi", "std", "synchapi", "winbase", "winuser"] }
|
||||
|
|
@ -53,21 +54,18 @@ ndk-glue = "0.2"
|
|||
jni = "0.17"
|
||||
|
||||
[[example]]
|
||||
name = "beep"
|
||||
path = "examples/beep.rs"
|
||||
name = "android"
|
||||
path = "examples/android.rs"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[[example]]
|
||||
name = "beep"
|
||||
|
||||
[[example]]
|
||||
name = "enumerate"
|
||||
path = "examples/enumerate.rs"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[[example]]
|
||||
name = "feedback"
|
||||
path = "examples/feedback.rs"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[[example]]
|
||||
name = "record_wav"
|
||||
path = "examples/record_wav.rs"
|
||||
crate-type = ["cdylib"]
|
||||
|
|
|
|||
65
examples/android.rs
Normal file
65
examples/android.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
extern crate anyhow;
|
||||
extern crate cpal;
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
|
||||
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))]
|
||||
fn main() {
|
||||
let host = cpal::default_host();
|
||||
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.expect("failed to find output device");
|
||||
|
||||
let config = device.default_output_config().unwrap();
|
||||
|
||||
match config.sample_format() {
|
||||
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()).unwrap(),
|
||||
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()).unwrap(),
|
||||
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
|
||||
where
|
||||
T: cpal::Sample,
|
||||
{
|
||||
let sample_rate = config.sample_rate.0 as f32;
|
||||
let channels = config.channels as usize;
|
||||
|
||||
// Produce a sinusoid of maximum amplitude.
|
||||
let mut sample_clock = 0f32;
|
||||
let mut next_value = move || {
|
||||
sample_clock = (sample_clock + 1.0) % sample_rate;
|
||||
(sample_clock * 440.0 * 2.0 * std::f32::consts::PI / sample_rate).sin()
|
||||
};
|
||||
|
||||
let err_fn = |err| eprintln!("an error occurred on stream: {}", err);
|
||||
|
||||
let stream = device.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
write_data(data, channels, &mut next_value)
|
||||
},
|
||||
err_fn,
|
||||
)?;
|
||||
stream.play()?;
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(1000));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32)
|
||||
where
|
||||
T: cpal::Sample,
|
||||
{
|
||||
for frame in output.chunks_mut(channels) {
|
||||
let value: T = cpal::Sample::from::<f32>(&next_sample());
|
||||
for sample in frame.iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +1,51 @@
|
|||
extern crate anyhow;
|
||||
extern crate clap;
|
||||
extern crate cpal;
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
|
||||
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))]
|
||||
fn main() {
|
||||
#[derive(Debug)]
|
||||
struct Opt {
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
jack: bool,
|
||||
|
||||
device: String,
|
||||
}
|
||||
|
||||
impl Opt {
|
||||
fn from_args() -> Self {
|
||||
let app = clap::App::new("beep").arg_from_usage("[DEVICE] 'The audio device to use'");
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
let app = app.arg_from_usage("-j, --jack 'Use the JACK host");
|
||||
let matches = app.get_matches();
|
||||
let device = matches.value_of("DEVICE").unwrap_or("default").to_string();
|
||||
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
return Opt {
|
||||
jack: matches.is_present("jack"),
|
||||
device,
|
||||
};
|
||||
|
||||
#[cfg(any(
|
||||
not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")),
|
||||
not(feature = "jack")
|
||||
))]
|
||||
Opt { device }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let opt = Opt::from_args();
|
||||
|
||||
// Conditionally compile with jack if the feature is specified.
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
|
|
@ -12,10 +53,7 @@ fn main() {
|
|||
))]
|
||||
// Manually check for flags. Can be passed through cargo with -- e.g.
|
||||
// cargo run --release --example beep --features jack -- --jack
|
||||
let host = if std::env::args()
|
||||
.collect::<String>()
|
||||
.contains(&String::from("--jack"))
|
||||
{
|
||||
let host = if opt.jack {
|
||||
cpal::host_from_id(cpal::available_hosts()
|
||||
.into_iter()
|
||||
.find(|id| *id == cpal::HostId::Jack)
|
||||
|
|
@ -32,19 +70,26 @@ fn main() {
|
|||
))]
|
||||
let host = cpal::default_host();
|
||||
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.expect("failed to find a default output device");
|
||||
let device = if opt.device == "default" {
|
||||
host.default_output_device()
|
||||
} else {
|
||||
host.output_devices()?
|
||||
.find(|x| x.name().map(|y| y == opt.device).unwrap_or(false))
|
||||
}
|
||||
.expect("failed to find output device");
|
||||
println!("Output device: {}", device.name()?);
|
||||
|
||||
let config = device.default_output_config().unwrap();
|
||||
println!("Default output config: {:?}", config);
|
||||
|
||||
match config.sample_format() {
|
||||
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()).unwrap(),
|
||||
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()).unwrap(),
|
||||
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()).unwrap(),
|
||||
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()),
|
||||
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()),
|
||||
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
|
||||
pub fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
|
||||
where
|
||||
T: cpal::Sample,
|
||||
{
|
||||
|
|
@ -55,7 +100,7 @@ where
|
|||
let mut sample_clock = 0f32;
|
||||
let mut next_value = move || {
|
||||
sample_clock = (sample_clock + 1.0) % sample_rate;
|
||||
(sample_clock * 440.0 * 2.0 * 3.141592 / sample_rate).sin()
|
||||
(sample_clock * 440.0 * 2.0 * std::f32::consts::PI / sample_rate).sin()
|
||||
};
|
||||
|
||||
let err_fn = |err| eprintln!("an error occurred on stream: {}", err);
|
||||
|
|
|
|||
|
|
@ -26,16 +26,16 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
if let Ok(conf) = device.default_input_config() {
|
||||
println!(" Default input stream config:\n {:?}", conf);
|
||||
}
|
||||
let mut input_configs = match device.supported_input_configs() {
|
||||
Ok(f) => f.peekable(),
|
||||
let input_configs = match device.supported_input_configs() {
|
||||
Ok(f) => f.collect(),
|
||||
Err(e) => {
|
||||
println!("Error: {:?}", e);
|
||||
continue;
|
||||
println!(" Error getting supported input configs: {:?}", e);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if input_configs.peek().is_some() {
|
||||
if !input_configs.is_empty() {
|
||||
println!(" All supported input stream configs:");
|
||||
for (config_index, config) in input_configs.enumerate() {
|
||||
for (config_index, config) in input_configs.into_iter().enumerate() {
|
||||
println!(
|
||||
" {}.{}. {:?}",
|
||||
device_index + 1,
|
||||
|
|
@ -49,16 +49,16 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
if let Ok(conf) = device.default_output_config() {
|
||||
println!(" Default output stream config:\n {:?}", conf);
|
||||
}
|
||||
let mut output_configs = match device.supported_output_configs() {
|
||||
Ok(f) => f.peekable(),
|
||||
let output_configs = match device.supported_output_configs() {
|
||||
Ok(f) => f.collect(),
|
||||
Err(e) => {
|
||||
println!("Error: {:?}", e);
|
||||
continue;
|
||||
println!(" Error getting supported output configs: {:?}", e);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if output_configs.peek().is_some() {
|
||||
if !output_configs.is_empty() {
|
||||
println!(" All supported output stream configs:");
|
||||
for (config_index, config) in output_configs.enumerate() {
|
||||
for (config_index, config) in output_configs.into_iter().enumerate() {
|
||||
println!(
|
||||
" {}.{}. {:?}",
|
||||
device_index + 1,
|
||||
|
|
|
|||
|
|
@ -7,15 +7,76 @@
|
|||
//! precisely synchronised.
|
||||
|
||||
extern crate anyhow;
|
||||
extern crate clap;
|
||||
extern crate cpal;
|
||||
extern crate ringbuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use ringbuf::RingBuffer;
|
||||
|
||||
const LATENCY_MS: f32 = 150.0;
|
||||
#[derive(Debug)]
|
||||
struct Opt {
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
jack: bool,
|
||||
|
||||
latency: f32,
|
||||
input_device: String,
|
||||
output_device: String,
|
||||
}
|
||||
|
||||
impl Opt {
|
||||
fn from_args() -> anyhow::Result<Self> {
|
||||
let app = clap::App::new("beep")
|
||||
.arg_from_usage(
|
||||
"-l, --latency [DELAY_MS] 'Specify the delay between input and output [default: 150]'",
|
||||
)
|
||||
.arg_from_usage("[IN] 'The input audio device to use'")
|
||||
.arg_from_usage("[OUT] 'The output audio device to use'");
|
||||
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
let app = app.arg_from_usage("-j, --jack 'Use the JACK host");
|
||||
let matches = app.get_matches();
|
||||
let latency: f32 = matches
|
||||
.value_of("latency")
|
||||
.unwrap_or("150")
|
||||
.parse()
|
||||
.context("parsing latency option")?;
|
||||
let input_device = matches.value_of("IN").unwrap_or("default").to_string();
|
||||
let output_device = matches.value_of("OUT").unwrap_or("default").to_string();
|
||||
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
return Ok(Opt {
|
||||
jack: matches.is_present("jack"),
|
||||
latency,
|
||||
input_device,
|
||||
output_device,
|
||||
});
|
||||
|
||||
#[cfg(any(
|
||||
not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")),
|
||||
not(feature = "jack")
|
||||
))]
|
||||
Ok(Opt {
|
||||
latency,
|
||||
input_device,
|
||||
output_device,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let opt = Opt::from_args()?;
|
||||
|
||||
fn main() -> Result<(), anyhow::Error> {
|
||||
// Conditionally compile with jack if the feature is specified.
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
|
|
@ -23,10 +84,7 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
))]
|
||||
// Manually check for flags. Can be passed through cargo with -- e.g.
|
||||
// cargo run --release --example beep --features jack -- --jack
|
||||
let host = if std::env::args()
|
||||
.collect::<String>()
|
||||
.contains(&String::from("--jack"))
|
||||
{
|
||||
let host = if opt.jack {
|
||||
cpal::host_from_id(cpal::available_hosts()
|
||||
.into_iter()
|
||||
.find(|id| *id == cpal::HostId::Jack)
|
||||
|
|
@ -43,21 +101,31 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
))]
|
||||
let host = cpal::default_host();
|
||||
|
||||
// Default devices.
|
||||
let input_device = host
|
||||
.default_input_device()
|
||||
.expect("failed to get default input device");
|
||||
let output_device = host
|
||||
.default_output_device()
|
||||
.expect("failed to get default output device");
|
||||
println!("Using default input device: \"{}\"", input_device.name()?);
|
||||
println!("Using default output device: \"{}\"", output_device.name()?);
|
||||
// Find devices.
|
||||
let input_device = if opt.input_device == "default" {
|
||||
host.default_input_device()
|
||||
} else {
|
||||
host.input_devices()?
|
||||
.find(|x| x.name().map(|y| y == opt.input_device).unwrap_or(false))
|
||||
}
|
||||
.expect("failed to find input device");
|
||||
|
||||
let output_device = if opt.output_device == "default" {
|
||||
host.default_output_device()
|
||||
} else {
|
||||
host.output_devices()?
|
||||
.find(|x| x.name().map(|y| y == opt.output_device).unwrap_or(false))
|
||||
}
|
||||
.expect("failed to find output device");
|
||||
|
||||
println!("Using input device: \"{}\"", input_device.name()?);
|
||||
println!("Using output device: \"{}\"", output_device.name()?);
|
||||
|
||||
// We'll try and use the same configuration between streams to keep it simple.
|
||||
let config: cpal::StreamConfig = input_device.default_input_config()?.into();
|
||||
|
||||
// Create a delay in case the input and output devices aren't synced.
|
||||
let latency_frames = (LATENCY_MS / 1_000.0) * config.sample_rate.0 as f32;
|
||||
let latency_frames = (opt.latency / 1_000.0) * config.sample_rate.0 as f32;
|
||||
let latency_samples = latency_frames as usize * config.channels as usize;
|
||||
|
||||
// The buffer to share samples
|
||||
|
|
@ -111,7 +179,7 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
// Play the streams.
|
||||
println!(
|
||||
"Starting the input and output streams with `{}` milliseconds of latency.",
|
||||
LATENCY_MS
|
||||
opt.latency
|
||||
);
|
||||
input_stream.play()?;
|
||||
output_stream.play()?;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! The input data is recorded to "$CARGO_MANIFEST_DIR/recorded.wav".
|
||||
|
||||
extern crate anyhow;
|
||||
extern crate clap;
|
||||
extern crate cpal;
|
||||
extern crate hound;
|
||||
|
||||
|
|
@ -11,19 +12,88 @@ use std::fs::File;
|
|||
use std::io::BufWriter;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Opt {
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
jack: bool,
|
||||
|
||||
device: String,
|
||||
}
|
||||
|
||||
impl Opt {
|
||||
fn from_args() -> Self {
|
||||
let app = clap::App::new("beep").arg_from_usage("[DEVICE] 'The audio device to use'");
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
let app = app.arg_from_usage("-j, --jack 'Use the JACK host");
|
||||
let matches = app.get_matches();
|
||||
let device = matches.value_of("DEVICE").unwrap_or("default").to_string();
|
||||
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
return Opt {
|
||||
jack: matches.is_present("jack"),
|
||||
device,
|
||||
};
|
||||
|
||||
#[cfg(any(
|
||||
not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")),
|
||||
not(feature = "jack")
|
||||
))]
|
||||
Opt { device }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), anyhow::Error> {
|
||||
// Use the default host for working with audio devices.
|
||||
let opt = Opt::from_args();
|
||||
|
||||
// Conditionally compile with jack if the feature is specified.
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
|
||||
feature = "jack"
|
||||
))]
|
||||
// Manually check for flags. Can be passed through cargo with -- e.g.
|
||||
// cargo run --release --example beep --features jack -- --jack
|
||||
let host = if opt.jack {
|
||||
cpal::host_from_id(cpal::available_hosts()
|
||||
.into_iter()
|
||||
.find(|id| *id == cpal::HostId::Jack)
|
||||
.expect(
|
||||
"make sure --features jack is specified. only works on OSes where jack is available",
|
||||
)).expect("jack host unavailable")
|
||||
} else {
|
||||
cpal::default_host()
|
||||
};
|
||||
|
||||
#[cfg(any(
|
||||
not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")),
|
||||
not(feature = "jack")
|
||||
))]
|
||||
let host = cpal::default_host();
|
||||
|
||||
// Setup the default input device and stream with the default input config.
|
||||
let device = host
|
||||
.default_input_device()
|
||||
.expect("Failed to get default input device");
|
||||
println!("Default input device: {}", device.name()?);
|
||||
// Setup the input device and stream with the default input config.
|
||||
let device = if opt.device == "default" {
|
||||
host.default_input_device()
|
||||
} else {
|
||||
host.input_devices()?
|
||||
.find(|x| x.name().map(|y| y == opt.device).unwrap_or(false))
|
||||
}
|
||||
.expect("failed to find input device");
|
||||
|
||||
println!("Input device: {}", device.name()?);
|
||||
|
||||
let config = device
|
||||
.default_input_config()
|
||||
.expect("Failed to get default input config");
|
||||
println!("Default input config: {:?}", config);
|
||||
|
||||
// The WAV file we're recording to.
|
||||
const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav");
|
||||
let spec = wav_spec_from_config(&config);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue