1 //! A basic output stream example, using an Output AudioUnit to generate a sine wave.
2
3 extern crate coreaudio;
4
5 use coreaudio::audio_unit::{AudioUnit, IOType, SampleFormat};
6 use coreaudio::audio_unit::render_callback::{self, data};
7 use std::f64::consts::PI;
8
9
10 // NOTE: temporary replacement for unstable `std::iter::iterate`
11 struct Iter {
12 value: f64,
13 }
14 impl Iterator for Iter {
15 type Item = f64;
next(&mut self) -> Option<f64>16 fn next(&mut self) -> Option<f64> {
17 self.value += 440.0 / 44_100.0;
18 Some(self.value)
19 }
20 }
21
22
main()23 fn main() {
24 run().unwrap()
25 }
26
run() -> Result<(), coreaudio::Error>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);
32
33 // Construct an Output audio unit that delivers audio to the default output device.
34 let mut audio_unit = try!(AudioUnit::new(IOType::DefaultOutput));
35
36 let stream_format = try!(audio_unit.output_stream_format());
37 println!("{:#?}", &stream_format);
38
39 // For this example, our sine wave expects `f32` data.
40 assert!(SampleFormat::F32 == stream_format.sample_format);
41
42 type Args = render_callback::Args<data::NonInterleaved<f32>>;
43 try!(audio_unit.set_render_callback(move |args| {
44 let Args { num_frames, mut data, .. } = args;
45 for i in 0..num_frames {
46 let sample = samples.next().unwrap();
47 for channel in data.channels_mut() {
48 channel[i] = sample;
49 }
50 }
51 Ok(())
52 }));
53 try!(audio_unit.start());
54
55 std::thread::sleep(std::time::Duration::from_millis(3000));
56
57 Ok(())
58 }
59