Why does the following code to play audio in the background not work?
I want to play audio in the background when I quit an application, but the following code does not appear to achieve this. What might I be doing wrong?
- (void)applicationDidEnterBackground:(UIApplication *)application
{
printf("hello");开发者_StackOverflow中文版
UIApplication *app = [UIApplication sharedApplication];
//beginBackgroundTaskWithExpirationHandler *bgTask;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{[theAudio play]; [app
endBackgroundTask:bgTask]; bgTask =UIBackgroundTaskInvalid;
NSString *path = [[NSBundle mainBundle] pathForResource:@"Piano"ofType:@"caf"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
// Do the work associated with the task.
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;;
NSLog(@"hello%@",bgTask);
}
An app cannot play sounds in the background unless the audio output was started before the app was put into the background.
You have a wrong order. Your code have to look like so:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
printf("hello");
UIApplication *app = [UIApplication sharedApplication];
//beginBackgroundTaskWithExpirationHandler *bgTask;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
// A handler to be called shortly before the application’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the application.
[theAudio pause];
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
// Do the work associated with the task.
NSString *path = [[NSBundle mainBundle] pathForResource:@"Piano"ofType:@"caf"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
NSLog(@"hello%@",bgTask);
}
精彩评论