当应用程序输入背景时播放音频

时间:2012-08-22 02:19:31

标签: iphone

我是iOS的新手。我有个问题。我想在应用程序在后台运行时播放音频。 我喜欢那样。

  

(void)applicationDidEnterBackground:(UIApplication *)application {

    NSLog(@"Application entered background state.");
// UIBackgroundTaskIdentifier bgTask is instance variable
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);

bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [application endBackgroundTask:self->bgTask];
        self->bgTask = UIBackgroundTaskInvalid;
    });
}];

dispatch_async(dispatch_get_main_queue(), ^{
            // play audio here
            NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error;
if (sound != nil) {
    [sound stop];
    [sound release];
    sound = nil;
}

sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
sound.numberOfLoops = -1;
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

if (sound == nil) {

}else {
    [sound setVolume:1.0];
    [sound play];
}
    [application endBackgroundTask:self->bgTask];
    self->bgTask = UIBackgroundTaskInvalid;
});

}

如果我在前台播放音频并输入主页按钮,则背景很好。但是当应用程序输入背景时我播放音频,它不起作用。我不知道为什么。

0 个答案:

没有答案