簡體   English   中英

AVPlayer從iOS 7后台通知播放音頻

[英]AVPlayer play audio from iOS 7 background notification

我在UIBackgroundModes設置了audiofetchremote-notification ,並且我的應用程序在后台(未激活)通過后台成功接收了遠程通知:

- (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中的應用程序可以像這樣從后台異步啟動音頻輸出嗎? 入睡后一段時間沒有產生任何聲音嗎?

您無法在后台啟動音頻。 audio背景模式允許您執行的唯一操作是在應用程序從前台轉到后台時繼續產生聲音。

這是一個完全合理的規則。 如果碰巧在后台運行的任何應用程序突然突然開始在設備中發出聲音,這將是可怕的,這會讓用戶感到困惑和煩惱!

但是,如果您的應用程序能夠接收遠程事件,並且已經發出聲音以使其成為遠程事件目標,則在audio背景模式下,它可以繼續作為遠程事件目標,從而可以在遠程事件目標中產生聲音。背景,只要在此期間沒有其他應用成為遠程事件目標即可。

在后台發出聲音的最可靠方法是將聲音附加到本地通知中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM