【发布时间】:2019-03-03 15:58:47
【问题描述】:
我目前正在尝试的是当应用在后台(或可能从挂起状态唤醒)收到远程通知时播放消息。
应用从挂起模式唤醒后,完全不播放声音。
当应用程序在前台时,调用didReceiveRemoteNotification:方法后立即播放声音。
当应用程序从挂起模式唤醒时调用didReceiveRemoteNotification: 方法时立即播放声音的合适方法是什么?
这是一些代码(语音管理器类):
-(void)textToSpeechWithMessage:(NSString*)message andLanguageCode:(NSString*)languageCode{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
DLog(@"Activating audio session");
if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers error:&error]) {
DLog(@"Unable to set audio session category: %@", error);
}
BOOL result = [audioSession setActive:YES error:&error];
if (!result) {
DLog(@"Error activating audio session: %@", error);
}else{
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:message];
[utterance setRate:0.5f];
[utterance setVolume:0.8f];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:languageCode];
[self.synthesizer speakUtterance:utterance];
}
}
-(void)textToSpeechWithMessage:(NSString*)message{
[self textToSpeechWithMessage:message andLanguageCode:[[NSLocale preferredLanguages] objectAtIndex:0]];
}
之后在AppDelegate:
[[MCSpeechManager sharedInstance] textToSpeechWithMessage:messageText];
我在 Capabilities->Background Modes 部分启用了 Audio、AirPlay 和 Picture in Picture 选项。
编辑:
如果需要,也许我应该启动一个后台任务并运行过期处理程序?我想这可能会奏效,但我也想听听解决这种情况的常用方法。
当我在后台收到通知时,使用此代码也会收到下一个错误:
激活音频会话时出错:Error Domain=NSOSStatusErrorDomain 代码=561015905“(空)”
代码 561015905 适用于:
AVAudioSessionErrorCodeCannotStartPlaying = '!pla', /* 0x21706C61, 561015905
它被描述为:
如果应用程序的信息属性列表出现此错误类型 不允许使用音频,或者如果应用程序在后台并使用 不允许背景音频的类别。
但我在其他类别(AVAudioSessionCategoryAmbient 和 AVAudioSessionCategorySoloAmbient)中遇到同样的错误
【问题讨论】:
-
我一拿到电脑就会添加这个信息。在应用程序挂起时调用 didReceiveRemoteNotification。意味着应用程序没有运行,手机可以被锁定或其他一些应用程序可以运行等。
-
@SwiftArchitect 收到远程通知时调用的方法是
application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo(注意它没有完成处理程序)。此外,在这里:developer.apple.com/reference/uikit/uiapplicationdelegate/… 我们可以发现只有当应用程序在前台运行时才会调用此方法......但据我所知,它是在我的应用程序处于暂停模式时调用的(它在休息时停止点我把上面的方法)。 -
引入:3.0,弃用:10.0。即使您找到了使用该路由的解决方案,它也会使用最终会被拒绝的已弃用 API。
-
虽然看起来不相关,但从后台播放音频需要 Info.plist 中的另一个特殊权限。我想在项目的 Info.plist 中设置 'UIBackgroundModes' = 'audio' 可能值得一试。请记住,此权限用于需要在后台播放音乐的应用程序。所有无线电应用程序都使用它。如果设置了此权限而没有具体说明您的应用需要此权限的原因,App Store 可能会拒绝您的应用。祝你好运!
-
@TarunTyagi 谢谢塔伦。实际上我确实启用了后台模式(请参阅我的问题)。我即将为此写支持票,因此最终会提供解决方案。
标签: ios objective-c avspeechsynthesizer background-mode avspeechutterance