2011-12-21 55 views
0

我的應用程序確實符合使用UIBackgroundModes設置爲'應用播放音頻'的要求。我的應用程序播放MPMusicPlayerController iPodMusicPlayer課程中的音樂。我試圖完成的是讓用戶設置一個計時器讓音樂停下來。我有這個問題。我已經實現了後臺任務在applicationDidEnterBackground方法如下:後臺服務「允許在後臺繼續運行」。那我爲什麼不能讓這個工作?

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    UIDevice* device = [UIDevice currentDevice]; 
    BOOL backgroundSupported = NO; 
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) { 
     backgroundSupported = device.multitaskingSupported; 
    } 

    if (backgroundSupported) { 
     UIApplication* app = [UIApplication sharedApplication]; 
     bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       if (bgTask != UIBackgroundTaskInvalid) { 
        [app endBackgroundTask:bgTask]; 
       } 
      }); 
     }]; 

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       if (bgTask != UIBackgroundTaskInvalid) { 
        if (rootController.sleepTimer != nil) 
        self.sustainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkTimeRemaining) userInfo:nil repeats:YES];  
       } 

      }); 
     }); 
    } 
} 

checkTimeRemaining方法:

-(void)checkTimeRemaining{ 
    NSTimeInterval totalSeconds = rootController.timerSetInSeconds.doubleValue; 
    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:rootController.startDateforSleepTimer]; 
    NSTimeInterval remainingTime = totalSeconds - elapsedTime; 
    NSLog(@"remaining time %f",remainingTime); 
    if (remainingTime <= 0) { 
     [self.musicPlayer pause]; 
     [sustainTimer invalidate]; 
     self.sustainTimer = nil; 
    } 
} 

我沒有得到任何錯誤,但計時器沒有超越允許10分鐘。由於我正在播放音頻(連同背景模式設定),我應該可以在指定的時間停止音樂。關於我要去哪裏的任何想法都是錯誤的?

感謝

回答

0

你不能得到它的工作,因爲背景音頻模式設置允許音頻處理,繼續在後臺,直到音頻停止。它不會授予對非音頻內容(如BackgroundTaskWithExpirationHandler)的任何特殊權限以繼續。

但是,如果您將時間記錄到音頻隊列或RemoteIO音頻單元緩衝區回調中,只要音頻繼續播放,它就會一直保持呼叫狀態。

+0

嗨,謝謝。在你描述的情況下,我還會使用iPodMusicPlayer控制器嗎?最適合學習如何實施的地方在哪裏?你認爲這是一些睡眠定時器應用程序如何實現這一目標?他們仍然可以使用iPod音樂控制器。 – sooper 2011-12-21 21:39:30

1

由於beginBackgroundTaskWithExpirationHandler只允許您執行有限長度的任務,所以您的計時器仍然限制在Apple規定的10分鐘時間限制內。另一方面,音頻框架允許設備在後臺播放音頻,直到用戶停止或音頻結束。

Playing Background Audio

當UIBackgroundModes鍵包含音頻值,該系統的 媒體框架自動防止從 對應的應用程序時,它移動到背景被暫停。只要它是 播放音頻或視頻內容,該應用程序將繼續在 背景中運行。但是,如果應用程序停止播放音頻或視頻,則系統會暫停播放。

+0

嗨,謝謝你回到我身邊。 AppStore中有幾個應用程序正在以某種方式執行此操作。他們使用iPodMusicPlayer控制器播放音樂,一旦用戶設置時間並鎖定設備,它將在x分鐘/小時後停止音樂。他們如何實現這一目標? – sooper 2011-12-21 21:37:22

+0

我的聲明的最後一行「或音頻結束」是您探索如何結束音頻的提示:)。看看@ hotpaw2推薦的內容。如果音頻隊列不斷回調你的代碼,你應該能夠阻止它。 – Joe 2011-12-21 21:40:19

+0

對不起,並沒有完全理解這一點。謝謝您的幫助。 – sooper 2011-12-21 21:41:56