tags:

views:

63

answers:

2

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");
     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);

}
A: 

An app cannot play sounds in the background unless the audio output was started before the app was put into the background.

hotpaw2
i also start play audio in the app after that i will paste same code in enterbackgound method
sidhu
A: 

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);

}