音频播放时在背景iOS中的应用程序

Dar*_*ren 11 audio background objective-c avaudioplayer ios

我有一个主要基于核心蓝牙的应用程序.当某些特定事件发生时,使用核心蓝牙背景模式唤醒应用程序并触发警报,但是当应用程序不在前台时,我无法使闹钟正常工作.

我有一个Alarm Singleton类,它初始化AVAudioPlayer如下:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                    pathForResource:soundName
                             ofType:@"caf"]];

self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[self.player prepareToPlay];
self.player.numberOfLoops = -1;
[self.player setVolume:1.0];

NSLog(@"%@", self.player);
Run Code Online (Sandbox Code Playgroud)

这是调用我的警报代码时调用的方法:

-(void)startAlert
{
    NSLog(@"%s", __FUNCTION__);

    playing = YES;
    [self.player play];
    NSLog(@"%i", self.player.playing);

    if (vibrate) {
        [self vibratePattern];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当应用程序位于前台时,self.player.playing返回1当应用程序在后台self.player.playing返回时0.为什么会这样?所有代码都被调用,因此应用程序清醒且运行正常.振动工作完美,使用AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

知道为什么这个声音不会播放?

谢谢

Mic*_*ner 13

Apple 在其文档中有一篇很好的技术问答文章(另请参阅播放和录制背景音频).

我认为缺少的一件事是你没有在Xcode设置中激活音频背景模式: 在此输入图像描述

也许还添加[self.player prepareToPlay]您的警报方法是有帮助的.


Pab*_*meu 9

我有一个应用程序,但也需要背景音频但我的应用程序使用应用程序后台模式"IP语音",因为它有时需要记录.我播放背景音频告诉应用程序单例我需要在后台播放音频:

UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
if([thePlayer play]){
    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];   
}
Run Code Online (Sandbox Code Playgroud)

编辑:您必须[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];在应用程序转到后台之前致电.在我的应用中,它是在你开始播放的同时,如果播放器可能在后台启动,你应该这样做:

- (void)applicationDidEnterBackground:(UIApplication *)application{
  // You should retain newTaskId to check for background tasks and finish them 
  newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];   
}
Run Code Online (Sandbox Code Playgroud)