最近在作運動相關的應用,須要在應用退到後臺的時候播放聲音,好比你已經跑了多少千米了,GPS信號很差,目標已達成等。code
剛開始使用了 AVAudioPlayer,實現了後臺播放的功能,但發現一個比較致命的問題:當其餘應用也播放聲音的時候就會被打斷!rem
後來研究了一下,使用System Sound Services能夠解決這個問題,代碼以下:it
#pragma mark - System Sound Services //播放多個文件 - (void)playWithWithFiles:(NSArray *)files { if (![files isValidArray] || files.count <= 0) { return; } [self stop]; [self.audioFiles removeAllObjects]; [self.audioFiles addObjectsFromArray:files]; [self playAudio:files.firstObject]; } //播放單個文件 - (void)playAudio:(NSString *)filePath { AudioServicesDisposeSystemSoundID(self.currentSoundID); NSURL *fileURL = [NSURL fileURLWithPath:filePath]; if (fileURL != nil) { SystemSoundID theSoundID; OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID); if (error == kAudioServicesNoError) { self.currentSoundID = theSoundID; AudioServicesAddSystemSoundCompletion(theSoundID, NULL, NULL, (void *)completionCallback, NULL); AudioServicesPlaySystemSound(theSoundID); } else { NSLog(@"Failed to create sound "); } } } //中止播放當前聲音 - (void)stop { [self.audioFiles removeAllObjects]; AudioServicesDisposeSystemSoundID(self.currentSoundID); } //播放完成後回調 void completionCallback(SystemSoundID mySSID) { AudioServicesDisposeSystemSoundID(mySSID); if ([VoiveManager sharedInstance].audioFiles.count > 0) { [[VoiveManager sharedInstance].audioFiles removeObjectAtIndex:0]; } if ([VoiveManager sharedInstance].audioFiles.count > 0) { [[VoiveManager sharedInstance] playAudio:[VoiveManager sharedInstance].audioFiles.firstObject]; } }
固然,使用System Sound Services也有它的限制:io