Cannot Control Volume of AVAudioPlayer via Hardware Buttons when AudioSessionActive is NO

巧了我就是萌 提交于 2019-12-06 00:45:40

In your case, you don't want to set the audio session inactive. What you need to do is use two methods, one to set the session up for playing a sound, and the other to set it up for being idle. The first method sets up a mix+duck audio mode, and the second uses a background-audio-friendly mode like ambient.

Something like this:

- (void)setActive {
    UInt32 mix  = 1;
    UInt32 duck = 1;
    NSError* errRet;

    AVAudioSession* session = [AVAudioSession sharedInstance];
    [session setActive:NO error:&errRet];

    [session setCategory:AVAudioSessionCategoryPlayback error:&errRet];
    NSAssert(errRet == nil, @"setCategory!");

    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(mix), &mix);
    AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(duck), &duck);

    [session setActive:YES error:&errRet];
}

- (void)setIdle {
    NSError* errRet;

    AVAudioSession* session = [AVAudioSession sharedInstance];
    [session setActive:NO error:&errRet];

    [session setCategory:AVAudioSessionCategoryAmbient error:&errRet];
    NSAssert(errRet == nil, @"setCategory!");

    [session setActive:YES error:&errRet];
}

Then to call it:

[self setActive];
[self _playAudio:nil];

To clean up after playing:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player
                   successfully:(BOOL)flag {
[self setIdle];

}

To be a good citizen, your app should set the audio session inactive when the it isn't navigating (i.e., performing its main function), but when it is, there is absolutely nothing wrong with keeping the audio session active and using modes to peacefully coexist with other apps. You can duplicate Apple's navigation app functionality using the code above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!