AVSpeechSynthesizer 后臺播放時電話中斷暫停和恢復播放報_BeginSpeaking: couldn't begin playback, 需要配置開啟后臺任務
1.在AppDelegate didFinishLaunchingWithOptions 中加入以下代碼
满哪、、劝篷、
NSError *error = NULL;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error) {
// Do some error handling
}
[session setActive:YES error:&error];
if (error) {
// Do some error handling
}
// 讓app支持接受遠程控制事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
哨鸭、、娇妓、
2.添加屬性
像鸡、、哈恰、
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier
backgroundTaskIdentifier;
只估、、着绷、
- 在applicationWillResignActive中加入如下代碼
蛔钙、、荠医、
// 開啟后臺處理多媒體事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// 后臺播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
_backgroundTaskIdentifier=[AppDelegate backgroundPlayerID:_backgroundTaskIdentifier];
// 其中的_bgTaskId是后臺任務UIBackgroundTaskIdentifier _bgTaskId;
吁脱、、彬向、
豫喧、、幢泼、
//實現(xiàn)一下backgroundPlayerID:這個方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:
(UIBackgroundTaskIdentifier)backTaskId{
//設置并激活音頻會話類別
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
//允許應用程序接收遠程控制
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//設置后臺任務ID
UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid){
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}