Introduce polymorphic stream constructors
This commit is contained in:
parent
78df791377
commit
076b814a15
5 changed files with 142 additions and 44 deletions
|
|
@ -21,14 +21,24 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
|
||||
let err_fn = |err| eprintln!("an error occurred on stream: {}", err);
|
||||
|
||||
let data_fn = move |data: &mut cpal::Data| match data.sample_format() {
|
||||
cpal::SampleFormat::F32 => write_data::<f32>(data, channels, &mut next_value),
|
||||
cpal::SampleFormat::I16 => write_data::<i16>(data, channels, &mut next_value),
|
||||
cpal::SampleFormat::U16 => write_data::<u16>(data, channels, &mut next_value),
|
||||
let stream = match format.data_type {
|
||||
cpal::SampleFormat::F32 => device.build_output_stream(
|
||||
&format.shape(),
|
||||
move |data: &mut [f32]| write_data(data, channels, &mut next_value),
|
||||
err_fn,
|
||||
)?,
|
||||
cpal::SampleFormat::I16 => device.build_output_stream(
|
||||
&format.shape(),
|
||||
move |data: &mut [i16]| write_data(data, channels, &mut next_value),
|
||||
err_fn,
|
||||
)?,
|
||||
cpal::SampleFormat::U16 => device.build_output_stream(
|
||||
&format.shape(),
|
||||
move |data: &mut [u16]| write_data(data, channels, &mut next_value),
|
||||
err_fn,
|
||||
)?,
|
||||
};
|
||||
|
||||
let stream = device.build_output_stream_raw(&format, data_fn, err_fn)?;
|
||||
|
||||
stream.play()?;
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(1000));
|
||||
|
|
@ -36,11 +46,10 @@ fn main() -> Result<(), anyhow::Error> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn write_data<T>(output: &mut cpal::Data, channels: usize, next_sample: &mut dyn FnMut() -> f32)
|
||||
fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32)
|
||||
where
|
||||
T: cpal::Sample,
|
||||
{
|
||||
let output = output.as_slice_mut::<T>().expect("unexpected sample type");
|
||||
for frame in output.chunks_mut(channels) {
|
||||
let value: T = cpal::Sample::from::<f32>(&next_sample());
|
||||
for sample in frame.iter_mut() {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue