2013-11-24 112 views
1

我正在构建一个正在运行的应用程序,通过音频通知用户他们需要开始运行或每隔几分钟开始步行。我能够让声音在后台运行,即使使用AVAudioPlayer的锁定屏幕也是如此。在后台运行声音并播放音乐

这里是什么,我有段:

ViewController.h

@property (nonatomic, strong) AVAudioPlayer *audioWalk; 

ViewController.m

- (void)viewDidLoad{ 
    [super viewDidLoad]; 
    // Walk Audio File 
    NSString *soundFile2 = [[NSBundle mainBundle] pathForResource:@"Walk" ofType:@"wav"]; 
    audioWalk = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile2] error:nil]; 

    // Load the audio into memory 
    [audioWalk prepareToPlay]; 

    // Permit the timer to run in the background 
    bgTask = 0; 
    UIApplication *app = [UIApplication sharedApplication]; 
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
    }]; 

    // Prevent the application from going to sleep while it is running 
    [UIApplication sharedApplication].idleTimerDisabled = YES; 

    // Starts recieving remote control events and is the first responder 
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
    [self becomeFirstResponder]; 

    // Plays audio 
    [audioWarmup play]; 

} 

我试图找出如何发挥出自己的声音,而不会中断在后台播放的音乐。此外,声音需要在后台播放,并且屏幕锁定。任何帮助将非常感激!

回答

0

我能解决它。以下是我在下面做的。这种解决方案允许音频文件在后台运行,即使是锁定屏幕,也不会中断或暂停来自其他应用程序(特别是音乐)的音频。

- (void)viewDidLoad{ 
    [super viewDidLoad]; 

    // Play audio even if lock screen is on, the with options allows audio from other applications to play without interruption 
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error:nil]; 

    // Walk Audio File 
    NSString *soundFile2 = [[NSBundle mainBundle] pathForResource:@"Walk" ofType:@"wav"]; 
    audioWalk = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile2] error:nil]; 

    // Load the audio into memory 
    [audioWalk prepareToPlay]; 

    // Permit the timer to run in the background 
    bgTask = 0; 
    UIApplication *app = [UIApplication sharedApplication]; 
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
    }]; 

    // Prevent the application from going to sleep while it is running 
    [UIApplication sharedApplication].idleTimerDisabled = YES; 

    // Starts receiving remote control events and is the first responder 
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
    [self becomeFirstResponder]; 

    // Plays audio 
    [audioWarmup play]; 

} 
+0

的setCategory任务必须一切与选项AVAudioSessionCategoryOptionMixWithOthers之前定义,否则将无法正常工作。 –