examples: Avoid f32 precision loss in beep example (#167)

This commit is contained in:
jansol 2017-10-20 18:12:01 +03:00 committed by tomaka
parent c28407b26d
commit 393206bde9
1 changed files with 13 additions and 17 deletions

View File

@ -12,19 +12,20 @@ fn main() {
let voice_id = event_loop.build_voice(&endpoint, &format).unwrap(); let voice_id = event_loop.build_voice(&endpoint, &format).unwrap();
event_loop.play(voice_id); event_loop.play(voice_id);
// Produce a sinusoid of maximum amplitude.
let samples_rate = format.samples_rate.0 as f32; let samples_rate = format.samples_rate.0 as f32;
let mut data_source = (0u64..).map(move |t| t as f32 * 440.0 * 2.0 * 3.141592 / samples_rate) // 440 Hz let mut sample_clock = 0f32;
.map(move |t| t.sin());
// Produce a sinusoid of maximum amplitude.
let mut next_value = || {
sample_clock = (sample_clock + 1.0) % samples_rate;
(sample_clock * 440.0 * 2.0 * 3.141592 / samples_rate).sin()
};
event_loop.run(move |_, buffer| { event_loop.run(move |_, buffer| {
match buffer { match buffer {
cpal::UnknownTypeBuffer::U16(mut buffer) => { cpal::UnknownTypeBuffer::U16(mut buffer) => {
for (sample, value) in buffer for sample in buffer.chunks_mut(format.channels.len()) {
.chunks_mut(format.channels.len()) let value = ((next_value() * 0.5 + 0.5) * std::u16::MAX as f32) as u16;
.zip(&mut data_source)
{
let value = ((value * 0.5 + 0.5) * std::u16::MAX as f32) as u16;
for out in sample.iter_mut() { for out in sample.iter_mut() {
*out = value; *out = value;
} }
@ -32,11 +33,8 @@ fn main() {
}, },
cpal::UnknownTypeBuffer::I16(mut buffer) => { cpal::UnknownTypeBuffer::I16(mut buffer) => {
for (sample, value) in buffer for sample in buffer.chunks_mut(format.channels.len()) {
.chunks_mut(format.channels.len()) let value = (next_value() * std::i16::MAX as f32) as i16;
.zip(&mut data_source)
{
let value = (value * std::i16::MAX as f32) as i16;
for out in sample.iter_mut() { for out in sample.iter_mut() {
*out = value; *out = value;
} }
@ -44,10 +42,8 @@ fn main() {
}, },
cpal::UnknownTypeBuffer::F32(mut buffer) => { cpal::UnknownTypeBuffer::F32(mut buffer) => {
for (sample, value) in buffer for sample in buffer.chunks_mut(format.channels.len()) {
.chunks_mut(format.channels.len()) let value = next_value();
.zip(&mut data_source)
{
for out in sample.iter_mut() { for out in sample.iter_mut() {
*out = value; *out = value;
} }