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".
|
|
|
|
|
|
|
|
extern crate cpal;
|
2019-06-21 12:55:21 +00:00
|
|
|
extern crate failure;
|
2018-02-12 13:10:24 +00:00
|
|
|
extern crate hound;
|
|
|
|
|
[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 cpal::{Device, EventLoop, Host};
|
|
|
|
|
2019-06-21 12:55:21 +00:00
|
|
|
fn main() -> Result<(), failure::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.
|
[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
|
|
|
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()?);
|
2018-02-12 13:10:24 +00:00
|
|
|
let format = device.default_input_format().expect("Failed to get default input format");
|
|
|
|
println!("Default input format: {:?}", format);
|
[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
|
|
|
let event_loop = host.event_loop();
|
2019-06-21 12:55:21 +00:00
|
|
|
let stream_id = event_loop.build_input_stream(&device, &format)?;
|
|
|
|
event_loop.play_stream(stream_id)?;
|
2018-02-12 13:10:24 +00:00
|
|
|
|
|
|
|
// 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)?;
|
2018-02-12 13:10:24 +00:00
|
|
|
let writer = std::sync::Arc::new(std::sync::Mutex::new(Some(writer)));
|
|
|
|
|
|
|
|
// A flag to indicate that recording is in progress.
|
|
|
|
println!("Begin recording...");
|
|
|
|
let recording = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
|
|
|
|
|
|
|
// Run the input stream on a separate thread.
|
|
|
|
let writer_2 = writer.clone();
|
|
|
|
let recording_2 = recording.clone();
|
|
|
|
std::thread::spawn(move || {
|
2019-06-21 22:10:40 +00:00
|
|
|
event_loop.run(move |id, event| {
|
|
|
|
let data = match event {
|
2019-06-24 18:43:27 +00:00
|
|
|
Ok(data) => data,
|
|
|
|
Err(err) => {
|
2019-06-24 18:57:01 +00:00
|
|
|
eprintln!("an error occurred on stream {:?}: {}", id, err);
|
2019-06-21 22:10:40 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
// If we're done recording, return early.
|
|
|
|
if !recording_2.load(std::sync::atomic::Ordering::Relaxed) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Otherwise write to the wav writer.
|
|
|
|
match data {
|
|
|
|
cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::U16(buffer) } => {
|
|
|
|
if let Ok(mut guard) = writer_2.try_lock() {
|
|
|
|
if let Some(writer) = guard.as_mut() {
|
|
|
|
for sample in buffer.iter() {
|
|
|
|
let sample = cpal::Sample::to_i16(sample);
|
|
|
|
writer.write_sample(sample).ok();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::I16(buffer) } => {
|
|
|
|
if let Ok(mut guard) = writer_2.try_lock() {
|
|
|
|
if let Some(writer) = guard.as_mut() {
|
|
|
|
for &sample in buffer.iter() {
|
|
|
|
writer.write_sample(sample).ok();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::F32(buffer) } => {
|
|
|
|
if let Ok(mut guard) = writer_2.try_lock() {
|
|
|
|
if let Some(writer) = guard.as_mut() {
|
|
|
|
for &sample in buffer.iter() {
|
|
|
|
writer.write_sample(sample).ok();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// Let recording go for roughly three seconds.
|
|
|
|
std::thread::sleep(std::time::Duration::from_secs(3));
|
|
|
|
recording.store(false, std::sync::atomic::Ordering::Relaxed);
|
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),
|
|
|
|
}
|
|
|
|
}
|