当iPhone被锁定时,AVAudioPlayer无法在后台播放

实际上我从文档目录中获取歌曲。

我引用了这个链接: – http://www.raywenderlich.com/29948/backgrounding-for-ios ,但它只播放来自捆绑的歌曲。 但我想播放文件目录中的歌曲。

我试过了

  1. Plist中的背景模式

  2. 应用程序不在背景中=否在Plist中

  3. 在Appdelegate didFinishLaunchingWithOptions: –

    NSError *setCategoryErr = nil; NSError *activationErr = nil; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr]; [[AVAudioSession sharedInstance] setActive:YES error:&activationErr]; 
  4. PlayMethod()

     { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:saveFileName]; NSURL *url1 = [[NSURL alloc] initFileURLWithPath: path]; self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:NULL]; [self.audioPlayer play]; self.seekBarSlider.minimumValue = 0.0f; self.seekBarSlider.maximumValue = self.audioPlayer.duration; //[self updateTime]; self.isPlaying=YES; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; _audioPlayer.delegate=self; NSError *error; UIBackgroundTaskIdentifier bgTaskId = 0; if (_audioPlayer == nil) NSLog([error description]); else{ UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid; [_audioPlayer prepareToPlay]; if([_audioPlayer play]){ newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; } if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; bgTaskId = newTaskId; } } 
  5. 数据保护:

      Under the Xcode -> capabilities . 

    所有我尝试但不工作! 谁能帮我。

当您的设备解锁时,它是否在后台运行?

如果是这样,它听起来像权限问题。 如果您已在developer.apple.com上为您的应用启用了数据保护function。 虽然设备使用密码锁定,但您将无法读取文档目录,因为文件已加密。

当设备被锁定时,我们试图写入数据库时​​遇到困难。 浪费了两天时间才弄明白。

w ^

  • 编辑 – 也可以在function下找到Xcode中的设置

我使用了数据保护机制,特别是在我要将NSDATA写入Documents目录之前。 我需要将Protection None设置为特定的文件路径。 所以我使用NSProtectionNone属性作为文件路径。 如果我们不设置ProtentionNone属性,Apple将不允许访问Locked State上的文件

 NSDictionary *protection = [NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey]; [[NSFileManager defaultManager] setAttributes:protection ofItemAtPath:_path error:nil]; if( [_rawData writeToFile:_path atomically:YES]) { NSLog(@"HOpefully written into Documentz directory.."); } else { NSLog(@"Writting file mechanism - Failed!"); } 

我曾经在App Bundle的无限循环中播放Dummy音频文件。 因此使用AVFoundation Framework连续播放虚拟音频文件。 所以我可以连续访问Documents目录音频文件。 逐个。

如果您将应用程序的Info.plistUIBackgroundModes键设置为audio ,则音频将在后台运行时继续播放。

audio:该应用程序在后台播放可听内容。

有关UIBackgroundModes更多信息,请点击此处

您的设备上是否还有其他音频/video应用正在运行? 其中一些也使用AVAudioSessionCategoryPlayback可以中断您的音频会话。

如何在Apple Developer上说 :

默认情况下,使用此类别意味着您的应用程序的音频不可混合 – 激活您的会话将中断任何其他也不可混合的音频会话。 要允许混合此类别,请使用AVAudioSessionCategoryOptionMixWithOthers选项。