I got a little lost with AVFoundation and you are my last hope!
I write a training application in which sometimes I play short tips, for example: “Pedal for 10 minutes” or “Good!”
Apple recommends activating the audio session immediately before playing the invitation and always deactivating it after the invitation starts. More than a recommendation, this is really what I want, because I use this option: AVAudioSessionCategoryOptionDuckOthers, and I just want to bite the music player during invitation playback, not earlier, but not after.
I do not know how to achieve this! Since I'm not very sure about deactivating an audio session, my first idea was to use a "while".
Here is my AudioController class:
#import "AudioController.h"
@interface AudioController ()
@property(strong,nonatomic)AVAudioPlayer *audioPlayerGood;
@end
@implementation AudioController
-(id)init
{
self=[super init];
if (self) {
[self configureAudioSession];
[self preparePlayers];
}
return self;
}
-(void)configureAudioSession
{
self.audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[self.audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&setCategoryError];
}
-(void)preparePlayers
{
NSError *initAudioPlayerError = nil;
NSURL *urlGood = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Correct" ofType:@"caf"]];
self.audioPlayerGood = [[AVAudioPlayer alloc] initWithContentsOfURL:urlGood error:&initAudioPlayerError];
if (initAudioPlayerError) {
NSLog(@"Error in audioPlayer: %@",[initAudioPlayerError localizedDescription]);
}
[self.audioPlayerGood prepareToPlay];
}
-(void)playCorrect
{
NSError *activationError = nil;
[self.audioSession setActive:YES error:&activationError];
[self.audioPlayerGood play];
NSLog(@"****************Correct played***************");
while (self.audioPlayerGood.playing) {
break;
}
[self.audioSession setActive:NO error:&activationError];
}
@end
Then, I initialize the AudioController object in another class, in which I use the playCorrect method:
[self.audioController playCorrect]
But immediately after playing the sound, the debug area prints this text to me:
AVAudioSession.mm:646: - [AVAudioSession setActive: withOptions: error:]: deactivate an audio session with I / O triggering. All input / output operations must be stopped or paused before the audio session is deactivated.
And if in ten seconds I want to play this sound again, it will not work, whereas the playCorrect method should activate the audio session ... Therefore, I don’t know how to deactivate the audio session correctly, and when it happens, if anyone can help with this :)