ios – 通过XCode中的AVAudioPlayer开始播放后台任务中的音频

我试图通过AVAudioPlayer从后台任务开始播放声音然后实例化,所以这就是我所拥有的.

为了便于阅读,我删除了所有用户选择的值.

- (void)restartHandler {
    bg = 0;
    bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }];
    tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes];
}

- (void)upd {
    if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) {
        [self playSoundFile];
        [tim invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }
}

- (void)playSoundFile {

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];


    // new player object
    _player = [[AVQueuePlayer alloc] init];
    [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil];

    [_player setVolume:.7];
    [_player play];

    NSLog(@"Testing");
}

说明:bg,tim,startDate,difference和_player是全局声明的变量.我从用户触发的方法调用 – (void)restartHandler,并在其内部启动一个10Hz的重复计时器 – (void)upd.当达到预设差异时,– (void)调用playSoundFile并启动并启动播放器.调用方法结束时的测试NSLog.

现在奇怪的是,如果我在应用程序处于活动状态时调用 – (void)playSoundFile,一切正常,但是如果我从后台任务启动它就不会播放任何声音.

任何帮助,提示,解决方案或抬头都非常感谢.

编辑

所以我尝试在运行时使用不同的线程,看起来,如果未在主线程上实例化Player,则会出现同样的问题.
我也试过使用AVPlayer和AVAudioPlayer,其中AVAudioPlayer的.playing属性确实返回YES并且仍然没有播放声音.

解决方法

从我在编写播放器应用程序后学到的内容来看,即使您已将所有内容配置正确,但当您的应用程序已在后台运行超过X秒时,您似乎无法开始播放音频.

要修复它,您必须明智地使用后台任务.
最重要的是你不能在playSoundFile之后立即调用endBackgroundTask.延迟约5-10秒.

以下是我为iOS6和iOS7管理的方法.

1,在plist中添加音频UIBackgroundModes.

2,设置音频会话类别:

3,在主线程中创建AVQueuePlayer,并在应用程序进入后台之前将音频资产排入队列.

*继续在后台播放(如播放播放列表)*

4,确保AVQueuePlayer中的音频队列永远不会变空,否则您的应用程序将在完成播放最后一个资产时被暂停.

5,如果5秒不足以让你获得下一个资产,你可以使用后台任务来延迟暂停.资产准备就绪后,您应该在10秒后调用endBackgroundTask.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...