我想要做的是让我的应用程序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);
}
}
}
我遇到的问题是,有时,音频会话会毫无问题地停止,而其他时候,音频会话将无法停止并出现以下错误:
错误域 = NSOSStatusErrorDomain 代码 = 2003329396 “操作无法完成。(OSStatus 错误 2003329396。)”
我不确定如何保证我可以停止 AVAudioSession。[[AVAudioSession sharedInstance] setActive:NO error:&error]
只要我无法停止音频会话,我就会一直打电话,但这似乎不起作用。任何帮助将不胜感激。谢谢!