一、前言
本周為APP集成了一個TTS聽書功能,遇到了些問題,在這里記錄下。
TTS聽書用的是京東TTS,SDK的用法這里就不在多說了,還是蠻簡單的。附上集成文檔:https://aidoc.jd.com/speech/tts.html
在集成完聽書功能后,鎖屏后發現APP內的TTS停止了播放。。。這就很尷尬,聽書肯定得在后台播放啊
研究了下,發現需要做一些設置。
二、處理
1、首先在 Signing&Capabilites 下的background Modes 先勾選Audio、、、
2、設置鎖屏播放下的視圖資源
直接上代碼
- (void)startSetupBackVoiceView { NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init]; [songDict setObjectSafely:self.chapterName aKey:MPMediaItemPropertyTitle];// 歌曲題目 [songDict setObjectSafely:@"TTS小一" aKey:MPMediaItemPropertyArtist];// 歌手名 [songDict setObjectSafely:self.bookName aKey:MPMediaItemPropertyAlbumTitle];// 專輯名 [songDict setObjectSafely:[NSNumber numberWithDouble:totalTime] aKey:MPMediaItemPropertyPlaybackDuration];// 歌曲時長 [songDict setObjectSafely:[NSNumber numberWithDouble:currentTime] aKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];// 已播時長 [songDict setObjectSafely:[NSNumber numberWithInteger:rate] aKey:MPNowPlayingInfoPropertyPlaybackRate]; // 播放速率 [songDict setObjectSafely:[[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"logoLogo"]] aKey:MPMediaItemPropertyArtwork]; // 圖片 [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict]; }
注:這里的信息很多都不需要填完整,看項目的需求,我們是小說TTS聽書功能,所以只填了一個歌曲題目和歌手名。
3、AppDelegete 里面的設置
- (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"applicationDidEnterBackground:"); [application beginReceivingRemoteControlEvents]; } - (void)applicationWillEnterForeground:(UIApplication *)application { NSLog(@"applicationWillEnterForeground:"); [application endReceivingRemoteControlEvents]; }
注:開啟后台播放模式
#pragma mark - 后台播放 - (BOOL)canBecomeFirstResponder { return YES; } - (void)remoteControlReceivedWithEvent:(UIEvent *)event { switch (event.subtype) { case UIEventSubtypeRemoteControlPlay: { [[HYJingDongTTSManager sharedJingDongTTS] resumeCompoundVoice]; } break; case UIEventSubtypeRemoteControlPause: { [[HYJingDongTTSManager sharedJingDongTTS] pauseCompoundVoice]; break; } case UIEventSubtypeRemoteControlPreviousTrack: {//上一曲 break; } case UIEventSubtypeRemoteControlNextTrack: {//下一曲 break; } case UIEventSubtypeRemoteControlTogglePlayPause: {//小窗口暫停 [[HYJingDongTTSManager sharedJingDongTTS] pauseCompoundVoice]; NSLog(@"---------點擊小窗口暫停按鈕"); break; } default: break; } }
注:這里是監測鎖屏下視圖的點擊事件,值得注意的是這個 UIEventSubtypeRemoteControlTogglePlayPause ,這個是點擊下拉設置頁面的小窗口的暫停事件,這個單獨提取出來了。
再運行下就好了,就會在鎖屏頁出現后台播放的視圖了。