@@ -34,13 +34,36 @@ impl Iterator for SineWaveGenerator {
3434}
3535
3636fn main ( ) -> Result < ( ) , coreaudio:: Error > {
37+ #[ cfg( any( target_os = "ios" , target_os = "visionos" , target_os = "tvos" ) ) ]
38+ unsafe {
39+ let session = objc2_avf_audio:: AVAudioSession :: sharedInstance ( ) ;
40+
41+ #[ cfg( target_os = "tvos" ) ]
42+ let _ = session. setCategory_error (
43+ objc2_avf_audio:: AVAudioSessionCategoryPlayback . expect ( "Failed to get option" )
44+ ) ;
45+ #[ cfg( any( target_os = "ios" , target_os = "tvos" ) ) ]
46+ let _ = session. setCategory_withOptions_error (
47+ objc2_avf_audio:: AVAudioSessionCategoryPlayAndRecord . expect ( "Failed to get options" ) ,
48+ objc2_avf_audio:: AVAudioSessionCategoryOptions :: DefaultToSpeaker ,
49+ ) ;
50+
51+ }
3752 let frequency_hz = 440. ;
3853 let volume = 0.15 ;
3954 let mut samples = SineWaveGenerator :: new ( frequency_hz, volume) ;
4055
4156 // Construct an Output audio unit that delivers audio to the default output device.
57+ #[ cfg( target_os = "macos" ) ]
4258 let mut audio_unit = AudioUnit :: new ( IOType :: DefaultOutput ) ?;
4359
60+ #[ cfg( any( target_os = "ios" , target_os = "visionos" , target_os = "tvos" ) ) ]
61+ let mut audio_unit = AudioUnit :: new ( coreaudio:: audio_unit:: IOType :: RemoteIO ) ?;
62+
63+ // iOS/tvOS/visionOS don't let you reconfigure an "initialized" audio unit, so uninitialize it
64+ #[ cfg( any( target_os = "ios" , target_os = "visionos" , target_os = "tvos" ) ) ]
65+ audio_unit. uninitialize ( ) ?;
66+
4467 // Read the input format. This is counterintuitive, but it's the format used when sending
4568 // audio data to the AudioUnit representing the output device. This is separate from the
4669 // format the AudioUnit later uses to send the data to the hardware device.
@@ -65,9 +88,13 @@ fn main() -> Result<(), coreaudio::Error> {
6588 }
6689 Ok ( ( ) )
6790 } ) ?;
91+ #[ cfg( any( target_os = "ios" , target_os = "visionos" , target_os = "tvos" ) ) ]
92+ audio_unit. initialize ( ) ?;
93+
6894 audio_unit. start ( ) ?;
95+ println ! ( "Audio started - playing 440Hz sine wave" ) ;
6996
70- std:: thread:: sleep ( std:: time:: Duration :: from_millis ( 3000 ) ) ;
97+ std:: thread:: sleep ( std:: time:: Duration :: from_millis ( 10_000 ) ) ;
7198
7299 Ok ( ( ) )
73100}
0 commit comments