1. 程式人生 > >iOS後臺語音播報

iOS後臺語音播報

最近做專案有一個需求: app在前臺彈出一個自定義提示框,並且語音讀出相關內容. app在後臺的時候彈出推送通知,並且語音讀出相關內容.

這個需求用到的知識點: 1,文字轉語音(iOS 7.0 之後自帶) 2,靜默推送(個推,jpush等,本人選用的是個推.個推帶有透傳功能,輕鬆實現需求1) **3,讓app在後臺時也能播報推送內容(我之前在網上找了好多內容,都沒有最後一步.最後在一篇後臺播放音樂的文章中找到一個方法.參考連結 http://www.jianshu.com/p/ab300ea6e90c).

實現: 1,文字轉語音

- (void)speakWithString:(NSString*)string
{
AVSpeechUtterance*utterance = [AVSpeechUtterancespeechUtteranceWithString:string];
utterance.pitchMultiplier=1.1;
//中式發音
AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoicevoiceWithLanguage:@"zh-TW"];
utterance.voice= voice;
AVSpeechSynthesizer*synth = [[AVSpeechSynthesizeralloc]init];
[synthspeakUtterance:utterance];
}

這是iOS 7 之後自帶的框架,裡面包括語速,語調等,需要的自己去百度.

2,靜默推送也是iOS自帶的具體就是讓後臺加一個欄位----->"content-available" : 1,推送的具體設定請自行參考自家文件,這裡不詳細說了.

3,這是最關鍵的一步,不做這一步的話app在後臺的時候是不能進行語音播報(或者只能播報一次)的!!!!!!!
在appDelegate中加入如下程式碼(再次宣告這一段程式碼參考:http://www.jianshu.com/p/ab300ea6e90c)

-(void)applicationWillResignActive:(UIApplication*)application
{
//開啟後臺處理多媒體事件
[[UIApplicationsharedApplication]beginReceivingRemoteControlEvents];
AVAudioSession*session=[AVAudioSessionsharedInstance];
[sessionsetActive:YESerror:nil];
//後臺播放
[sessionsetCategory:AVAudioSessionCategoryPlaybackerror:nil];
//這樣做,可以在按home鍵進入後臺後 ,播放一段時間,幾分鐘吧。但是不能持續播放網路歌曲,若需要持續播放網路歌曲,還需要申請後臺任務id,具體做法是:
_bgTaskId=[AppDelegatebackgroundPlayerID:_bgTaskId];
//其中的_bgTaskId是後臺任務UIBackgroundTaskIdentifier _bgTaskId;
}
//實現一下backgroundPlayerID:這個方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
//設定並激活音訊會話類別
AVAudioSession*session=[AVAudioSessionsharedInstance];
[sessionsetCategory:AVAudioSessionCategoryPlaybackerror:nil];
[sessionsetActive:YESerror:nil];
//允許應用程式接收遠端控制
[[UIApplicationsharedApplication]beginReceivingRemoteControlEvents];
//設定後臺任務ID
UIBackgroundTaskIdentifiernewTaskId=UIBackgroundTaskInvalid;
newTaskId=[[UIApplicationsharedApplication]beginBackgroundTaskWithExpirationHandler:nil];
if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
{
[[UIApplicationsharedApplication]endBackgroundTask:backTaskId];
}
returnnewTaskId;
}

然後就是專案配置要選對,留圖供大家參考


Paste_Image.png

這樣後臺語音播報的功能就實現了,但是隻有app沒被系統殺死的情況下才能語音播報,如果app長時間在後臺導致被系統殺死,播報功能就沒有了,這個我還不知道怎麼解決!歡迎各位大神留言指導!