在背景持續播音樂

只有生命中真正重要的事,才可以在App進入背景後持續進行。例如聽音樂。

1.勾選Capabilities頁面裡,Background Modes的Audio, AirPlay, and Picture in Picture

勾選後將自動在App的Info頁面新增 App plays audio or streams audio/video using AirPlay

2.加入AVFoundation

import AVFoundation

3.設定AVAudioSession的category,讓音樂在背景可以繼續播放。

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch {

}

4.播放音樂

let url = NSBundle.mainBundle().URLForResource("小幸運", withExtension: "m4a")
try! self.player = AVAudioPlayer(contentsOfURL: url!)
self.player.numberOfLoops = -1
self.player.play()

results matching ""

    No results matching ""