AVAudioSession and AVAudioPlayer
To take full control over the sound routing and when
Play audio through Receiver (earpiece speaker)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
BOOL toSpeaker; AVAudioSessionCategoryOptions options = AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP; // Setup audio session auto audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]; // setting category to PlayAndRecord if (toSpeaker) [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil]; // routing audio to Speaker else [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil]; // routing audio to Receiver [audioSession setActive:YES withOptions:0 error:nil]; // activating the session // Loading sound NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audioFile" ofType:@"mp3"]]; if (url != nil) { soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [soundPlayer prepareToPlay]; } // Sound play if (soundPlayer) [soundPlayer play]; |
Link to gist with extension I’ve created to deal with category changes.