我想要做的是,在后台音频应用正在播放音频时,允许我的应用程序使用
在我的
每当我想要说出新的话语时,我会执行以下操作。我遵循了《AVSpeechSynthesizer存在的问题,有什么解决方法?》中所提到的建议,每次创建一个新的AVSpeechSynthesizer来“确保”始终接收到取消操作(它似乎有效,但我不确定原因)。
在我的AVSpeechSynthesizer代理方法中,我会检查是否应该停止音频会话以将背景音量恢复到正常水平,如果当前的AVSpeechSynthesizer和当前的AVSpeechUtterance与最后已知的合成器和话语相匹配。
我遇到的问题是,有时音频会话可以正常停止,但有时却无法停止,并出现以下错误:
AVSpeechSynthesizer
发出话语。 当我的应用正在说话时,我希望背景应用程序的音频会“减弱”,然后在我的应用结束说话后返回其原始音量。在我的
AudioFeedback
类中,我这样初始化设置AVAudioSessions
: self.session = [AVAudioSession sharedInstance];
NSError *error;
[self.session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&error];
每当我想要说出新的话语时,我会执行以下操作。我遵循了《AVSpeechSynthesizer存在的问题,有什么解决方法?》中所提到的建议,每次创建一个新的AVSpeechSynthesizer来“确保”始终接收到取消操作(它似乎有效,但我不确定原因)。
- (AVSpeechUtterance *) utteranceWithString: (NSString *) string
{
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-ES"];
[utterance setRate:(AVSpeechUtteranceDefaultSpeechRate+AVSpeechUtteranceMinimumSpeechRate)/2.0];
return utterance;
}
- (void) sayString: (NSString *) string cancelPrevious: (BOOL) cancelPrevious
{
[self.session setActive:enabled error:nil];
if (cancelPrevious) {
AVSpeechSynthesizer *oldSynthesizer = self.voice;
self.voice = nil;
[oldSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
self.voice = [[AVSpeechSynthesizer alloc] init];
self.voice.delegate = self;
}
// Keep track of the final utterance, we'll use this to determine whether or not we should stop the audio session
self.finalUtterance = [self utteranceWithString:string];
[self.voice speakUtterance:self.finalUtterance];
}
在我的AVSpeechSynthesizer代理方法中,我会检查是否应该停止音频会话以将背景音量恢复到正常水平,如果当前的AVSpeechSynthesizer和当前的AVSpeechUtterance与最后已知的合成器和话语相匹配。
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
NSError *error;
// Only stop the audio session if this is the last created synthesizer
if (synthesizer == self.voice && self.finalUtterance == utterance) {
if ([self.session setActive:enabled error:&error]]) {
NSLog(@"Stopped the audio session: Speech synthesizer still speaking %d", synthesizer.speaking);
} else {
NSLog(@"ERROR failed to stop the audio session: %@. Speech synthesizer still speaking %d", error, synthesizer.speaking);
}
}
}
我遇到的问题是,有时音频会话可以正常停止,但有时却无法停止,并出现以下错误:
我不确定如何保证能够成功停止 AVAudioSession。我尝试在无法停止音频会话时不断调用Error Domain=NSOSStatusErrorDomain Code=2003329396 "The operation couldn’t be completed. (OSStatus error 2003329396.)"
[[AVAudioSession sharedInstance] setActive:NO error:&error]
,但这似乎没有奏效。希望能得到帮助,非常感谢!