Add an Android example and enhance the other examples with CLI argument parsing.
This commit is contained in:
parent
f6c12257bb
commit
269c60fde0
7 changed files with 222 additions and 53 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"
|
||||
structopt = "0.3.21"
|
||||
|
||||
[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"] }
|
||||
|
|
@ -52,22 +53,27 @@ ndk = "0.2"
|
|||
ndk-glue = "0.2"
|
||||
jni = "0.17"
|
||||
|
||||
[[example]]
|
||||
name = "android"
|
||||
path = "examples/android.rs"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[[example]]
|
||||
name = "beep"
|
||||
path = "examples/beep.rs"
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["bin"]
|
||||
|
||||
[[example]]
|
||||
name = "enumerate"
|
||||
path = "examples/enumerate.rs"
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["bin"]
|
||||
|
||||
[[example]]
|
||||
name = "feedback"
|
||||
path = "examples/feedback.rs"
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["bin"]
|
||||
|
||||
[[example]]
|
||||
name = "record_wav"
|
||||
path = "examples/record_wav.rs"
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["bin"]
|
||||
|
|
|
|||
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,27 @@
|
|||
extern crate anyhow;
|
||||
extern crate cpal;
|
||||
extern crate structopt;
|
||||
|
||||
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.
|
||||
#[cfg(all(
|
||||
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.
|
||||
// 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 +46,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 +76,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,
|
||||
|
|
|
|||
|
|
@ -9,13 +9,35 @@
|
|||
extern crate anyhow;
|
||||
extern crate cpal;
|
||||
extern crate ringbuf;
|
||||
extern crate structopt;
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
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> {
|
||||
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"),
|
||||
|
|
@ -23,10 +45,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 +62,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 +140,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()?;
|
||||
|
|
|
|||
|
|
@ -5,25 +5,71 @@
|
|||
extern crate anyhow;
|
||||
extern crate cpal;
|
||||
extern crate hound;
|
||||
extern crate structopt;
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use std::fs::File;
|
||||
use std::io::BufWriter;
|
||||
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> {
|
||||
// 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