2014-01-07 52 views
1

我已經audio,通過fetchUIBackgroundModesremote-notification集,我成功地接收在後臺(未激活)與我的應用程序的遠程通知:AVPlayer從iOS的7背景通知播放音頻

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 

我有以下我:- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

self.audioPlayer = [[AVPlayer alloc] init]; 

NSError *sessionError = nil; 
NSError *activationError = nil; 
[[AVAudioSession sharedInstance] setActive:YES error:&activationError]; 
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&sessionError]) { 
    NSLog(@"[AppDelegate] Failed to setup audio session: %@", sessionError); 
} 

而在- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler我有以下幾點:

  NSLog(@"Playing url: %@", filePath); 

      AVPlayerItem * currentItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:filePath]]; 

      [self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem]; 
      [self.audioPlayer play]; 

我看到這個代碼通過NSLog執行,但沒有聲音產生。實際上,如果應用程序在幾秒鐘內收到通知,那麼音頻會播放,也就是說。它第一次獲得音頻播放的通知,但從來沒有。

iOS 7中的應用程序是否可以像這樣異步啓動音頻輸出,即從後臺開始,即。它已經睡着了,而且沒有產生任何音頻一段時間?

回答

0

您不能在後臺啓動音頻。 audio背景模式允許您做的唯一事情就是在應用從前景到背景時繼續播放聲音。

這是一個完全合理的規則。如果任何碰巧在後臺運行的應用程序可能會突然開始從設備中隨時隨地產生聲音,這對用戶的神祕和煩惱會很糟糕!但是,如果您的應用程序能夠接收遠程事件,並且它已經產生了聲音以便它是遠程事件目標,那麼,使用audio背景模式,它可以繼續作爲遠程事件目標,並因此可以繼續在後臺產生聲音,只要沒有其他應用成爲遠程事件目標。

在後臺產生聲音的最可靠方法是將聲音附加到本地通知。

+0

謝謝。本地通知是否可以從應用程序的「NSDocumentDirectory」或僅編譯的資源中播放聲音資源? – mrblog

+1

必須在應用程序包中,您可以看到爲什麼:本地通知可能會從現在開始播放,因此我們需要保證聲音文件仍然存在。此外,它必須是一個系統警報類型的聲音(即aiff/wav),因爲沒有聲音解碼資源可以爲你帶來效果。當然,聲音必須很短。 – matt