AVAudioPlayer在应用进入后台时无法播放

3

我正在尝试使用AVFoundationFramework

目前,我能够在前台运行AVAudioPlayer。 当应用程序进入后台时,AVAudioPlayer不会继续播放。

实现的确切步骤如下:

  1. Adding Background Tasks to the .plist

    enter image description here

  2. Setting up AVAudioPlayer

    self.objAVAudioPlayer = [[AVAudioPlayer alloc]initWithData:mp3Data error:&error];
    self.objAVAudioPlayer.delegate = self;
    
  3. Setting up AVAudioSession

    if([self.objAVAudioPlayer prepareToPlay])
    {
        AVAudioSession *objAVAudioSession = [AVAudioSession sharedInstance];
        [objAVAudioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
        [objAVAudioSession setActive:YES
                                         error:nil];
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self.objAVAudioPlayer play];
    }
    

当应用程序恢复时,它会从之前离开的地方继续。

基本SDK版本为iOS 7.0

有什么想法是我漏掉了什么?任何帮助都将不胜感激。


你的“- (void)applicationDidEnterBackground:(UIApplication *)application”中有什么? - Aluminum
applicationDidEnterBackground 中还没有实现任何代码。 - footyapps27
您的应用程序ID是否启用了应用程序间音频授权? - ZeMoon
你需要将它包装在一个后台任务中。 - Daij-Djan
所以我必须明确地将它放在另一个线程中或在applicationDidEnterBackground中处理它。 - footyapps27
@akashg:我正在模拟器中测试它。我还使用了开发人员配置文件在设备上测试它。结果一样!! - footyapps27
1个回答

1

要在后台模式下播放音频,您应该设置AVAudioSession并添加以下代码

UIBackgroundTaskIdentifier backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
    [application endBackgroundTask:backgroundTask]; //Tell the system that we are done with the tasks
    backgroundTask = UIBackgroundTaskInvalid; //Set the task to be invalid
 }];

将以下内容添加到您的AppDelegate.m类中的方法中。
- (void)applicationDidEnterBackground:(UIApplication *)application {
    //Some code
}

一个小更新 - 我分享的代码在 iOS 设备中似乎运行良好。只有模拟器存在问题。 - footyapps27

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接