Add an Android example and enhance the other examples with CLI argument parsing.

This commit is contained in:
Alex Moon 2020-12-14 10:56:14 -07:00
parent f6c12257bb
commit 269c60fde0
7 changed files with 222 additions and 53 deletions

View file

@ -262,6 +262,8 @@ jobs:
toolchain: stable toolchain: stable
override: true override: true
target: armv7-linux-androideabi target: armv7-linux-androideabi
- name: Check android
run: cargo check --example android --target armv7-linux-androideabi --verbose
- name: Check beep - name: Check beep
run: cargo check --example beep --target armv7-linux-androideabi --verbose run: cargo check --example beep --target armv7-linux-androideabi --verbose
- name: Check enumerate - name: Check enumerate
@ -284,4 +286,4 @@ jobs:
- name: Install Cargo APK - name: Install Cargo APK
run: cargo install cargo-apk run: cargo install cargo-apk
- name: Build APK - name: Build APK
run: cargo apk build --example beep run: cargo apk build --example android

View file

@ -18,6 +18,7 @@ thiserror = "1.0.2"
anyhow = "1.0.12" anyhow = "1.0.12"
hound = "3.4" hound = "3.4"
ringbuf = "0.2" ringbuf = "0.2"
structopt = "0.3.21"
[target.'cfg(target_os = "windows")'.dependencies] [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"] } winapi = { version = "0.3", features = ["audiosessiontypes", "audioclient", "coml2api", "combaseapi", "debug", "devpkey", "handleapi", "ksmedia", "mmdeviceapi", "objbase", "profileapi", "std", "synchapi", "winbase", "winuser"] }
@ -52,22 +53,27 @@ ndk = "0.2"
ndk-glue = "0.2" ndk-glue = "0.2"
jni = "0.17" jni = "0.17"
[[example]]
name = "android"
path = "examples/android.rs"
crate-type = ["cdylib"]
[[example]] [[example]]
name = "beep" name = "beep"
path = "examples/beep.rs" path = "examples/beep.rs"
crate-type = ["cdylib"] crate-type = ["bin"]
[[example]] [[example]]
name = "enumerate" name = "enumerate"
path = "examples/enumerate.rs" path = "examples/enumerate.rs"
crate-type = ["cdylib"] crate-type = ["bin"]
[[example]] [[example]]
name = "feedback" name = "feedback"
path = "examples/feedback.rs" path = "examples/feedback.rs"
crate-type = ["cdylib"] crate-type = ["bin"]
[[example]] [[example]]
name = "record_wav" name = "record_wav"
path = "examples/record_wav.rs" path = "examples/record_wav.rs"
crate-type = ["cdylib"] crate-type = ["bin"]

65
examples/android.rs Normal file
View 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;
}
}
}

View file

@ -1,10 +1,27 @@
extern crate anyhow; extern crate anyhow;
extern crate cpal; extern crate cpal;
extern crate structopt;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "beep", about = "Simple example of audio playback.")]
struct Opt {
#[cfg(all(
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
feature = "jack"
))]
#[structopt(short, long)]
jack: bool,
#[structopt(default_value = "default")]
device: String,
}
fn main() -> anyhow::Result<()> {
let opt = Opt::from_args();
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))]
fn main() {
// Conditionally compile with jack if the feature is specified. // Conditionally compile with jack if the feature is specified.
#[cfg(all( #[cfg(all(
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
@ -12,10 +29,7 @@ fn main() {
))] ))]
// Manually check for flags. Can be passed through cargo with -- e.g. // Manually check for flags. Can be passed through cargo with -- e.g.
// cargo run --release --example beep --features jack -- --jack // cargo run --release --example beep --features jack -- --jack
let host = if std::env::args() let host = if opt.jack {
.collect::<String>()
.contains(&String::from("--jack"))
{
cpal::host_from_id(cpal::available_hosts() cpal::host_from_id(cpal::available_hosts()
.into_iter() .into_iter()
.find(|id| *id == cpal::HostId::Jack) .find(|id| *id == cpal::HostId::Jack)
@ -32,19 +46,26 @@ fn main() {
))] ))]
let host = cpal::default_host(); let host = cpal::default_host();
let device = host let device = if opt.device == "default" {
.default_output_device() host.default_output_device()
.expect("failed to find a 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(); let config = device.default_output_config().unwrap();
println!("Default output config: {:?}", config);
match config.sample_format() { match config.sample_format() {
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()).unwrap(), cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()),
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()).unwrap(), cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()),
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()).unwrap(), 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 where
T: cpal::Sample, T: cpal::Sample,
{ {
@ -55,7 +76,7 @@ where
let mut sample_clock = 0f32; let mut sample_clock = 0f32;
let mut next_value = move || { let mut next_value = move || {
sample_clock = (sample_clock + 1.0) % sample_rate; 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); let err_fn = |err| eprintln!("an error occurred on stream: {}", err);

View file

@ -26,16 +26,16 @@ fn main() -> Result<(), anyhow::Error> {
if let Ok(conf) = device.default_input_config() { if let Ok(conf) = device.default_input_config() {
println!(" Default input stream config:\n {:?}", conf); println!(" Default input stream config:\n {:?}", conf);
} }
let mut input_configs = match device.supported_input_configs() { let input_configs = match device.supported_input_configs() {
Ok(f) => f.peekable(), Ok(f) => f.collect(),
Err(e) => { Err(e) => {
println!("Error: {:?}", e); println!(" Error getting supported input configs: {:?}", e);
continue; Vec::new()
} }
}; };
if input_configs.peek().is_some() { if !input_configs.is_empty() {
println!(" All supported input stream configs:"); 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!( println!(
" {}.{}. {:?}", " {}.{}. {:?}",
device_index + 1, device_index + 1,
@ -49,16 +49,16 @@ fn main() -> Result<(), anyhow::Error> {
if let Ok(conf) = device.default_output_config() { if let Ok(conf) = device.default_output_config() {
println!(" Default output stream config:\n {:?}", conf); println!(" Default output stream config:\n {:?}", conf);
} }
let mut output_configs = match device.supported_output_configs() { let output_configs = match device.supported_output_configs() {
Ok(f) => f.peekable(), Ok(f) => f.collect(),
Err(e) => { Err(e) => {
println!("Error: {:?}", e); println!(" Error getting supported output configs: {:?}", e);
continue; Vec::new()
} }
}; };
if output_configs.peek().is_some() { if !output_configs.is_empty() {
println!(" All supported output stream configs:"); 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!( println!(
" {}.{}. {:?}", " {}.{}. {:?}",
device_index + 1, device_index + 1,

View file

@ -9,13 +9,35 @@
extern crate anyhow; extern crate anyhow;
extern crate cpal; extern crate cpal;
extern crate ringbuf; extern crate ringbuf;
extern crate structopt;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::RingBuffer; use ringbuf::RingBuffer;
use structopt::StructOpt;
const LATENCY_MS: f32 = 150.0; #[derive(Debug, StructOpt)]
#[structopt(name = "beep", about = "Simple example of audio playback.")]
struct Opt {
#[cfg(all(
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
feature = "jack"
))]
#[structopt(short, long)]
jack: bool,
#[structopt(short, long, default_value = "150.0")]
latency: f32,
#[structopt(default_value = "default")]
input_device: String,
#[structopt(default_value = "default")]
output_device: String,
}
fn main() -> Result<(), anyhow::Error> { fn main() -> Result<(), anyhow::Error> {
let opt = Opt::from_args();
// Conditionally compile with jack if the feature is specified. // Conditionally compile with jack if the feature is specified.
#[cfg(all( #[cfg(all(
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
@ -23,10 +45,7 @@ fn main() -> Result<(), anyhow::Error> {
))] ))]
// Manually check for flags. Can be passed through cargo with -- e.g. // Manually check for flags. Can be passed through cargo with -- e.g.
// cargo run --release --example beep --features jack -- --jack // cargo run --release --example beep --features jack -- --jack
let host = if std::env::args() let host = if opt.jack {
.collect::<String>()
.contains(&String::from("--jack"))
{
cpal::host_from_id(cpal::available_hosts() cpal::host_from_id(cpal::available_hosts()
.into_iter() .into_iter()
.find(|id| *id == cpal::HostId::Jack) .find(|id| *id == cpal::HostId::Jack)
@ -43,21 +62,31 @@ fn main() -> Result<(), anyhow::Error> {
))] ))]
let host = cpal::default_host(); let host = cpal::default_host();
// Default devices. // Find devices.
let input_device = host let input_device = if opt.input_device == "default" {
.default_input_device() host.default_input_device()
.expect("failed to get default input device"); } else {
let output_device = host host.input_devices()?
.default_output_device() .find(|x| x.name().map(|y| y == opt.input_device).unwrap_or(false))
.expect("failed to get default output device"); }
println!("Using default input device: \"{}\"", input_device.name()?); .expect("failed to find input device");
println!("Using default output device: \"{}\"", output_device.name()?);
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. // We'll try and use the same configuration between streams to keep it simple.
let config: cpal::StreamConfig = input_device.default_input_config()?.into(); let config: cpal::StreamConfig = input_device.default_input_config()?.into();
// Create a delay in case the input and output devices aren't synced. // 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; let latency_samples = latency_frames as usize * config.channels as usize;
// The buffer to share samples // The buffer to share samples
@ -111,7 +140,7 @@ fn main() -> Result<(), anyhow::Error> {
// Play the streams. // Play the streams.
println!( println!(
"Starting the input and output streams with `{}` milliseconds of latency.", "Starting the input and output streams with `{}` milliseconds of latency.",
LATENCY_MS opt.latency
); );
input_stream.play()?; input_stream.play()?;
output_stream.play()?; output_stream.play()?;

View file

@ -5,25 +5,71 @@
extern crate anyhow; extern crate anyhow;
extern crate cpal; extern crate cpal;
extern crate hound; extern crate hound;
extern crate structopt;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use std::fs::File; use std::fs::File;
use std::io::BufWriter; use std::io::BufWriter;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "beep", about = "Simple example of audio playback.")]
struct Opt {
#[cfg(all(
any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"),
feature = "jack"
))]
#[structopt(short, long)]
jack: bool,
#[structopt(default_value = "default")]
device: String,
}
fn main() -> Result<(), anyhow::Error> { 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(); let host = cpal::default_host();
// Setup the default input device and stream with the default input config. // Setup the input device and stream with the default input config.
let device = host let device = if opt.device == "default" {
.default_input_device() host.default_input_device()
.expect("Failed to get default input device"); } else {
println!("Default input device: {}", device.name()?); 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 let config = device
.default_input_config() .default_input_config()
.expect("Failed to get default input config"); .expect("Failed to get default input config");
println!("Default input config: {:?}", config); println!("Default input config: {:?}", config);
// The WAV file we're recording to. // The WAV file we're recording to.
const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav"); const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav");
let spec = wav_spec_from_config(&config); let spec = wav_spec_from_config(&config);