2010-10-06 39 views
1

我想在退出應用程序時在後臺播放音頻,但下面的代碼似乎並未實現此目的。我可能會做錯什麼?爲什麼下面的代碼在後臺播放音頻不起作用?

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

} 

回答

0

應用程序無法在後臺播放聲音,除非音頻輸出在應用程序放入後臺之前啓動。

+0

我也開始在應用程序中播放音頻之後,我將在enterbackgound方法中粘貼相同的代碼 – sidhu 2010-10-07 06:26:06

0

訂單錯誤。您的代碼必須如下所示:

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

} 
相關問題