Skip to content

Commit 0cbf885

Browse files
Merge pull request #66 from JoshMcguigan/modernize-example
modernize sine example
2 parents 08c8b79 + d9c1a6d commit 0cbf885

File tree

1 file changed

+30
-22
lines changed

1 file changed

+30
-22
lines changed

examples/sine.rs

+30-22
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,49 @@ use coreaudio::audio_unit::{AudioUnit, IOType, SampleFormat};
66
use coreaudio::audio_unit::render_callback::{self, data};
77
use std::f64::consts::PI;
88

9-
10-
// NOTE: temporary replacement for unstable `std::iter::iterate`
11-
struct Iter {
12-
value: f64,
9+
struct SineWaveGenerator {
10+
time: f64,
11+
/// generated frequency in Hz
12+
freq: f64,
13+
/// magnitude of generated signal
14+
volume: f64,
1315
}
14-
impl Iterator for Iter {
15-
type Item = f64;
16-
fn next(&mut self) -> Option<f64> {
17-
self.value += 440.0 / 44_100.0;
18-
Some(self.value)
16+
17+
impl SineWaveGenerator {
18+
fn new(freq: f64, volume: f64) -> Self {
19+
SineWaveGenerator {
20+
time: 0.,
21+
freq,
22+
volume,
23+
}
1924
}
2025
}
2126

22-
23-
fn main() {
24-
run().unwrap()
27+
impl Iterator for SineWaveGenerator {
28+
type Item = f32;
29+
fn next(&mut self) -> Option<f32> {
30+
self.time += 1. / 44_100.;
31+
let output = ((self.freq * self.time * PI * 2.).sin() * self.volume) as f32;
32+
Some(output)
33+
}
2534
}
2635

27-
fn run() -> Result<(), coreaudio::Error> {
28-
29-
// 440hz sine wave generator.
30-
let mut samples = Iter { value: 0.0 }
31-
.map(|phase| (phase * PI * 2.0).sin() as f32 * 0.15);
36+
fn main() -> Result<(), coreaudio::Error> {
37+
let frequency_hz = 440.;
38+
let volume = 0.15;
39+
let mut samples = SineWaveGenerator::new(frequency_hz, volume);
3240

3341
// Construct an Output audio unit that delivers audio to the default output device.
34-
let mut audio_unit = try!(AudioUnit::new(IOType::DefaultOutput));
42+
let mut audio_unit = AudioUnit::new(IOType::DefaultOutput)?;
3543

36-
let stream_format = try!(audio_unit.output_stream_format());
44+
let stream_format = audio_unit.output_stream_format()?;
3745
println!("{:#?}", &stream_format);
3846

3947
// For this example, our sine wave expects `f32` data.
4048
assert!(SampleFormat::F32 == stream_format.sample_format);
4149

4250
type Args = render_callback::Args<data::NonInterleaved<f32>>;
43-
try!(audio_unit.set_render_callback(move |args| {
51+
audio_unit.set_render_callback(move |args| {
4452
let Args { num_frames, mut data, .. } = args;
4553
for i in 0..num_frames {
4654
let sample = samples.next().unwrap();
@@ -49,8 +57,8 @@ fn run() -> Result<(), coreaudio::Error> {
4957
}
5058
}
5159
Ok(())
52-
}));
53-
try!(audio_unit.start());
60+
})?;
61+
audio_unit.start()?;
5462

5563
std::thread::sleep(std::time::Duration::from_millis(3000));
5664

0 commit comments

Comments
 (0)