Swift — 做個播放器吧(背景播放)
3 min readJun 13, 2018
雖然上次教學後我們播放器的功能也算是完成了,但這次我想擴充一個很常用的功能也很實際的功能,那就是背景播放,該如何持續在背景播放我們的音樂呢?
首先我們先到我們專案下的 Targets > Capabilities 底下的 Background Mode 設置為 ON,之後再把我們的 Audio, AirPlay, and Picture in Piture 給勾選:
之後我們到我們的 AppDelegate 先 import 我們的 AVFoundation ,之後再到didFinishLaunchingWithOptions launchOptions 底下加上:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {let audioSession = AVAudioSession.sharedInstance()do {
// 使用指定的選項啟動或停用 APP 的 Audio Session。
try audioSession.setActive(true)
// 設置 audioSession 類別為 AVAudioSessionCategoryPlayback
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
} catch { print(error)}
return true
}
如此一來就算 APP 離開我們畫面,音樂還是會持續播放下去。有更多的詳細的處理方式請參考 Apple 官方文件,這篇文章因為撞到挑戰賽所以篇幅稍短請見諒: