AVAudioSession mixing with AVSpeechUtterance

邮差的信 提交于 2019-12-04 19:31:36

I just wanted to let everyone know that after some troubleshooting, this is how I was able to solve my issue. I am not sure I like the solution, and am working to improve it.

View Did Load

    - (void)viewDidLoad
    {
            syn = [[AVSpeechSynthesizer alloc] init];
            syn.delegate = self;

            iPodMusicPlayer = [[MPMusicPlayerController alloc] init];
    }

Speech Function

    -(void)speak:(NSString *)string
    {

            audioSession = [AVAudioSession sharedInstance];

            NSError *setCategoryError = nil;
            NSError *activationError = nil;
            BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback
                withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];

            [audioSession setActive:YES error:&activationError];

            if(audioSession.isOtherAudioPlaying){
                wasPlaying = YES;
                NSLog(@"Other audio is playing");
                [iPodMusicPlayer pause];
            }

            NSLog(@"Success %hhd", success);

            AVSpeechUtterance *utterance = [AVSpeechUtterance           speechUtteranceWithString:string];
            utterance.rate = 0.3f;
            utterance.volume = 1.0;
            [syn speakUtterance:utterance];
     }

AVSpeechSynthesizer Delegate method that gets called after the speech is finished

     - (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
     {
            if(wasPlaying){
                NSLog(@"Start Playing");
               [iPodMusicPlayer play];
               wasPlaying = NO;
            }
     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!