MPMusicPlayerController和AVSpeechSynthesizer试图实现ducking

时间:2016-08-07 19:20:13

标签: ios mpmusicplayercontroller avspeechsynthesizer

我第一次在应用程序中使用MPMusicPlayerController和AVSpeechSynthesizer类。它是一个正在运行的应用程序,可播放音乐(使用MPMusicPlayerController)并每隔5分钟使用统计信息更新跑步者(使用AVSpeechSynthesizer)。它工作正常,但音乐和广播的音量相同,所以根据播放的歌曲,可能很难听到统计数据,所以现在我希望在统计数据播放时音乐音量降低。以下代码仅用于在统计数据开始播放时减少音乐音量,但在统计数据播出结束后它不会恢复音乐,这当然是我想要它做的。我正在使用此帖Setting iOS MPMusicPlayerController volume relative to AVAudioPlayer中的此解决方案。 我的代码如下:

- (void)setAudioSessionWithDucking:(BOOL)isDucking
    {
    AudioSessionSetActive(NO);

    UInt32 overrideCategoryDefaultToSpeaker = 1;
    AudioSessionSetProperty     (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof     (overrideCategoryDefaultToSpeaker), &overrideCategoryDefaultToSpeaker);

    UInt32 overrideCategoryMixWithOthers = 1;
    AudioSessionSetProperty     (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof     (overrideCategoryMixWithOthers), &overrideCategoryMixWithOthers);

    UInt32 value = isDucking;
    AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck,     sizeof(value), &value);

    AudioSessionSetActive(YES);
}

- (void)updateLabels
{

if(fmod(mins,5) == 0){
 [self setAudioSessionWithDucking:YES];

    AVSpeechUtterance *utterance = [AVSpeechUtterance
                                    speechUtteranceWithString:newText];
    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];

    utterance.rate = 0.45;
    utterance.pitchMultiplier = 0.95;
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"];
    utterance.volume = 1.0;

    [synth speakUtterance:utterance];

 [self setAudioSessionWithDucking:NO];
         }
}

1 个答案:

答案 0 :(得分:0)

使用此功能告诉其他应用可以恢复音频播放:

-(void)notifyIOSthatOtherAppsCanResumeAudioPlayback{
    NSError *err;
    [indigoAudioSession setActive: NO
                  withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                        error: &err];
    if(err!=nil){
        NSLog(@"audioIsFreeNotificationForIOS ERROR: %@",err.description);
    }
}

如果您要恢复的音频来自您自己的应用,您可以告诉它从此委托方法恢复播放:

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
    playSomeMusic();

}