iOSアプリでオーディオ再生を実装する際に、アプリがバックグラウンドになっても再生し続けるようにする設定手順です。
必要な設定は2つです。
- Capabilities設定で、Background Modes - Audio をONにする。
- AVAudioSession のカテゴリをPlaybackに設定する。
Capabilities設定からBackground Modesを設定する
プロジェクトファイルを選択肢、「TARGETS」からアプリ名をクリックし、「Capabilities」を選択します。
この中の、 「Background Modes」をON に変更します。
さらに、「Modes」の中から、「Audio. AirPlay. and Picture in Picture」のチェックボックスをONにします。
以下の画面は、これらの設定をした後の画面です。
AVAudioSession のカテゴリをPlaybackに設定する
続いて、AVAudioSessionの設定を行います。
AVAudioSessionは、アプリでオーディオをどのように扱うかを宣言するためのオブジェクトです。
例えば、他のアプリで音声再生をしているときの挙動や、バックグラウンドでの音声再生の挙動などを扱うことができます。
AVAudioSession - Apple Developer Document
AppDelegateにて、AVAudioSessionのCategory設定を変更してやります。
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
/// AVAudioSessionCategory設定
let session = AVAudioSession.sharedInstance()
do {
// CategoryをPlaybackにする
try session.setCategory(.playback, mode: .default)
} catch {
// 予期しない場合
fatalError("Category設定失敗")
}
// session有効化
do {
try session.setActive(true)
} catch {
// 予期しない場合
fatalError("Session有効化失敗")
}
return true
}
以上でオーディオ再生時をアプリがバックグラウンドに移動しても継続できるようになります。