ios - iPhone 锁定时,AVAudioPlayer 不会在后台播放

标签 ios iphone objective-c avaudioplayer avplayer

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

我提到了这个链接:- http://www.raywenderlich.com/29948/backgrounding-for-ios ,但它只会播放 bundle 中的歌曲。但我想播放文档目录中的歌曲。

我试过了

  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 上为您的应用程序启用了数据保护。当设备被密码锁定时,您将无法读取文档目录,因为文件已加密。

当设备被锁定时,我们在尝试写入数据库时​​遇到了困难。浪费了整整两天的时间来解决这个问题。

W

  • 编辑 - 还可以在 Xcode 的功能下找到设置

关于ios - iPhone 锁定时,AVAudioPlayer 不会在后台播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21875213/

相关文章:

objective-c - 将事件连接到 UITextView

ios - 从 iPhone 的日历中删除事件

ios - 我可以在开始导航之前阅读 SKStreetType 信息吗?

ios - 如何为核心数据中的属性替换或设置新值?

iphone - 什么是 UIGobblerGestureRecognizer?

iphone - Objective-C 2.0中的多线程问题

ios - 有人知道如何修复选择器错误吗?

ios - 使用计时器更新当前 View 中的数据

iphone - iOS 开发 : How can I induce low memory warnings on device?

iphone - 启用 Guard Malloc 时 UIImagePNGRepresentation 中的 EXC_BAD_ACCESS 错误