簡體   English   中英

通過Xcode中的AVAudioPlayer開始播放后台任務中的音頻

[英]start playing audio from a background task via AVAudioPlayer in Xcode

我試圖通過AVAudioPlayer從后台任務開始播放聲音然后實例化,所以這就是我所擁有的。

為了便於閱讀,我刪除了所有用戶選擇的值。

- (void)restartHandler {
    bg = 0;
    bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }];
    tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes];
}

- (void)upd {
    if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) {
        [self playSoundFile];
        [tim invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }
}

- (void)playSoundFile {

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];


    // new player object
    _player = [[AVQueuePlayer alloc] init];
    [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil];

    [_player setVolume:.7];
    [_player play];

    NSLog(@"Testing");
}

說明: bgtimstartDatedifference_player是全局聲明的變量。 我從用戶觸發的方法調用- (void)restartHandler ,並在其內部啟動一個10Hz的重復計時器- (void)upd 當達到預設差異時, - (void)playSoundFile調用- (void)playSoundFile並啟動並啟動播放器。 調用方法結束時的測試NSLog。

現在奇怪的是,如果我在應用程序處於活動狀態時調用- (void)playSoundFile ,一切正常,但是如果我從后台任務啟動它就不會播放任何聲音。

編輯

所以我嘗試在運行時使用不同的線程,看起來,如果未在主線程上實例化Player,則會出現同樣的問題。 我也試過使用AVPlayerAVAudioPlayer ,其中AVAudioPlayer.playing屬性確實返回YES,但仍然沒有播放聲音。

根據我在編寫播放器應用程序后學到的內容,即使您已將所有內容配置正確,但當您的應用程序已在后台運行超過X秒時,您似乎無法開始播放音頻。

要修復它,您必須明智地使用后台任務。 最重要的是你不能playSoundFile之后立即調用endBackgroundTask 延遲約5-10秒。

以下是我為iOS6和iOS7管理的方法。

1,在plist中添加音頻UIBackgroundModes。

2,設置音頻會話類別:

3,在主線程中創建AVQueuePlayer,並在應用程序進入后台之前將音頻資產排入隊列

* 繼續在后台播放(如播放播放列表) *

4,確保AVQueuePlayer中的音頻隊列永遠不會變空 ,否則您的應用程序將在完成播放最后一個資產時被暫停。

5,如果5秒不足以讓你獲得下一個資產,你可以使用后台任務來延遲暫停。 資產准備就緒后,您應該在10秒后調用endBackgroundTask

在下面包含你的playSoundFile調用,這應該總是在主線程中運行它

dispatch_async(dispatch_get_main_queue(), ^{

});

將此if添加到- (void) playSoundFile以檢查是否創建了播放器,如果沒有,則創建它

if(!_player) {
    _player = [[AVQueuePlayer alloc] init];
}

對我來說好像你沒有設置合適的背景模式? Xcode截圖

此外,看起來像另一個用戶有相同的問題,並使用Apple Docs帖子修復它。 鏈接到郵政

您可能只需要執行將音頻會話設置為活動的步驟:

[audioSession setActive:YES error:&activationError];

希望能幫助到你!

如果你需要開始在后台播放聲音(沒有一個技巧,比如繼續播放音量為零,直到你需要聲音):

  • 在p.list中設置背景模式音頻;
  • 將AudioSession類別設置為AVAudioSessionCategoryPlayback
  • 將AudioSession設置為活動狀態
  • 當您的背景應用程序運行時,在播放聲音之前啟動后台任務(顯然當剩余背景時間少於10秒時,聲音不會播放)

這對我來說很有用。

對我來說固定的是在應用程序退出時開始播放一些音頻,所以我在appDelegate的applicationWillResignActive中添加了1秒的空白音頻

func applicationWillResignActive(_ application: UIApplication) {

        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask(true)
        })


        let secSilence = URL(fileURLWithPath: Bundle.main.path(forResource: "1secSilence", ofType: "mp3")!)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: secSilence)
        }
        catch {
            print("Error in loading sound file")
        }

        audioPlayer.prepareToPlay()
        audioPlayer.play()



}

暫無
暫無

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

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