13
14

More than 5 years have passed since last update.

[Swift4] バックグラウンドでオーディオ再生する

Posted at

iOSアプリでオーディオ再生を実装する際に、アプリがバックグラウンドになっても再生し続けるようにする設定手順です。

必要な設定は2つです。

  1. Capabilities設定で、Background Modes - Audio をONにする。
  2. AVAudioSession のカテゴリをPlaybackに設定する。

Capabilities設定からBackground Modesを設定する

プロジェクトファイルを選択肢、「TARGETS」からアプリ名をクリックし、「Capabilities」を選択します。

この中の、 「Background Modes」をON に変更します。
さらに、「Modes」の中から、「Audio. AirPlay. and Picture in Picture」のチェックボックスをONにします。

以下の画面は、これらの設定をした後の画面です。

スクリーンショット 2019-04-09 16.45.14.png

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
    }

以上でオーディオ再生時をアプリがバックグラウンドに移動しても継続できるようになります。

13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14