@@ -6,41 +6,49 @@ use coreaudio::audio_unit::{AudioUnit, IOType, SampleFormat};
6
6
use coreaudio:: audio_unit:: render_callback:: { self , data} ;
7
7
use std:: f64:: consts:: PI ;
8
8
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 ,
13
15
}
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
+ }
19
24
}
20
25
}
21
26
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
+ }
25
34
}
26
35
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) ;
32
40
33
41
// 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 ) ? ;
35
43
36
- let stream_format = try! ( audio_unit. output_stream_format ( ) ) ;
44
+ let stream_format = audio_unit. output_stream_format ( ) ? ;
37
45
println ! ( "{:#?}" , & stream_format) ;
38
46
39
47
// For this example, our sine wave expects `f32` data.
40
48
assert ! ( SampleFormat :: F32 == stream_format. sample_format) ;
41
49
42
50
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| {
44
52
let Args { num_frames, mut data, .. } = args;
45
53
for i in 0 ..num_frames {
46
54
let sample = samples. next ( ) . unwrap ( ) ;
@@ -49,8 +57,8 @@ fn run() -> Result<(), coreaudio::Error> {
49
57
}
50
58
}
51
59
Ok ( ( ) )
52
- } ) ) ;
53
- try! ( audio_unit. start ( ) ) ;
60
+ } ) ? ;
61
+ audio_unit. start ( ) ? ;
54
62
55
63
std:: thread:: sleep ( std:: time:: Duration :: from_millis ( 3000 ) ) ;
56
64
0 commit comments