2018-02-12 13:10:24 +00:00
|
|
|
//! Records a WAV file (roughly 3 seconds long) using the default input device and format.
|
|
|
|
//!
|
|
|
|
//! The input data is recorded to "$CARGO_MANIFEST_DIR/recorded.wav".
|
|
|
|
|
2019-10-13 10:36:49 +00:00
|
|
|
extern crate anyhow;
|
2018-02-12 13:10:24 +00:00
|
|
|
extern crate cpal;
|
|
|
|
extern crate hound;
|
|
|
|
|
2019-07-09 06:47:33 +00:00
|
|
|
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
2020-01-13 14:27:41 +00:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::BufWriter;
|
2020-01-20 19:35:23 +00:00
|
|
|
use std::sync::{Arc, Mutex};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
|
2019-10-13 10:36:49 +00:00
|
|
|
fn main() -> Result<(), anyhow::Error> {
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
// Use the default host for working with audio devices.
|
|
|
|
let host = cpal::default_host();
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
// Setup the default input device and stream with the default input format.
|
2019-07-09 06:47:33 +00:00
|
|
|
let device = host
|
|
|
|
.default_input_device()
|
|
|
|
.expect("Failed to get default input device");
|
2019-06-21 12:55:21 +00:00
|
|
|
println!("Default input device: {}", device.name()?);
|
2019-07-09 06:47:33 +00:00
|
|
|
let format = device
|
|
|
|
.default_input_format()
|
|
|
|
.expect("Failed to get default input format");
|
2018-02-12 13:10:24 +00:00
|
|
|
println!("Default input format: {:?}", format);
|
|
|
|
// The WAV file we're recording to.
|
|
|
|
const PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav");
|
|
|
|
let spec = wav_spec_from_format(&format);
|
2019-06-21 12:55:21 +00:00
|
|
|
let writer = hound::WavWriter::create(PATH, spec)?;
|
2020-01-13 14:27:41 +00:00
|
|
|
let writer = Arc::new(Mutex::new(Some(writer)));
|
2018-02-12 13:10:24 +00:00
|
|
|
|
|
|
|
// A flag to indicate that recording is in progress.
|
|
|
|
println!("Begin recording...");
|
|
|
|
|
|
|
|
// Run the input stream on a separate thread.
|
|
|
|
let writer_2 = writer.clone();
|
2020-01-13 14:27:41 +00:00
|
|
|
|
|
|
|
let err_fn = move |err| {
|
2019-07-15 13:37:03 +00:00
|
|
|
eprintln!("an error occurred on stream: {}", err);
|
2020-01-13 14:27:41 +00:00
|
|
|
};
|
|
|
|
|
2020-01-20 19:35:23 +00:00
|
|
|
let data_fn = move |data: &cpal::Data| match data.sample_format() {
|
|
|
|
cpal::SampleFormat::F32 => write_input_data::<f32, f32>(data, &writer_2),
|
|
|
|
cpal::SampleFormat::I16 => write_input_data::<i16, i16>(data, &writer_2),
|
|
|
|
cpal::SampleFormat::U16 => write_input_data::<u16, i16>(data, &writer_2),
|
2020-01-19 14:06:19 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let stream = device.build_input_stream(&format, data_fn, err_fn)?;
|
2020-01-13 14:27:41 +00:00
|
|
|
|
2019-07-09 06:47:33 +00:00
|
|
|
stream.play()?;
|
2018-02-12 13:10:24 +00:00
|
|
|
|
|
|
|
// Let recording go for roughly three seconds.
|
|
|
|
std::thread::sleep(std::time::Duration::from_secs(3));
|
2019-07-09 06:47:33 +00:00
|
|
|
drop(stream);
|
2019-06-21 12:55:21 +00:00
|
|
|
writer.lock().unwrap().take().unwrap().finalize()?;
|
2018-02-12 13:10:24 +00:00
|
|
|
println!("Recording {} complete!", PATH);
|
2019-06-21 12:55:21 +00:00
|
|
|
Ok(())
|
2018-02-12 13:10:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat {
|
|
|
|
match format {
|
|
|
|
cpal::SampleFormat::U16 => hound::SampleFormat::Int,
|
|
|
|
cpal::SampleFormat::I16 => hound::SampleFormat::Int,
|
|
|
|
cpal::SampleFormat::F32 => hound::SampleFormat::Float,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn wav_spec_from_format(format: &cpal::Format) -> hound::WavSpec {
|
|
|
|
hound::WavSpec {
|
|
|
|
channels: format.channels as _,
|
|
|
|
sample_rate: format.sample_rate.0 as _,
|
|
|
|
bits_per_sample: (format.data_type.sample_size() * 8) as _,
|
|
|
|
sample_format: sample_format(format.data_type),
|
|
|
|
}
|
|
|
|
}
|
2020-01-13 14:27:41 +00:00
|
|
|
|
|
|
|
type WavWriterHandle = Arc<Mutex<Option<hound::WavWriter<BufWriter<File>>>>>;
|
|
|
|
|
2020-01-19 14:06:19 +00:00
|
|
|
fn write_input_data<T, U>(input: &cpal::Data, writer: &WavWriterHandle)
|
2020-01-13 14:27:41 +00:00
|
|
|
where
|
|
|
|
T: cpal::Sample,
|
|
|
|
U: cpal::Sample + hound::Sample,
|
|
|
|
{
|
2020-01-19 14:06:19 +00:00
|
|
|
let input = input.as_slice::<T>().expect("unexpected sample format");
|
2020-01-13 14:27:41 +00:00
|
|
|
if let Ok(mut guard) = writer.try_lock() {
|
|
|
|
if let Some(writer) = guard.as_mut() {
|
|
|
|
for &sample in input.iter() {
|
|
|
|
let sample: U = cpal::Sample::from(&sample);
|
|
|
|
writer.write_sample(sample).ok();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|