2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】オーディオの出力変更を検知する

Last updated at Posted at 2024-01-06

始めに

有線のイヤホンやairpodsなどが端末と接続されオーディオの出力先が変更したとき、これを検知することができますが、少し躓いたので書き留めておきます。

本題

import SwiftUI
import AVFoundation

class AudioSessionManager: ObservableObject {
    @Published var headphonesConnected: Bool = false

    init() {
        do {
            try AVAudioSession.sharedInstance().setActive(true) // この処理がなくて躓いた
            print("AVAudioSession is now active")
        } catch {
            print("Failed to activate AVAudioSession. Error: \(error)")
        }
        let nc = NotificationCenter.default
        nc.addObserver(
            self,
            selector: #selector(handleRouteChange(_:)),
            name: AVAudioSession.routeChangeNotification,
            object: nil
        )
    }

    @objc func handleRouteChange(_ notification: Notification) {
        print("Route Change")
        guard let userInfo = notification.userInfo,
              let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
              let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
            return
        }

        switch reason {
        case .newDeviceAvailable:
            headphonesConnected = true
            if headphonesConnected {
                print("イヤホンが接続されました。")
            }

        case .oldDeviceUnavailable:
            headphonesConnected = false
            if !headphonesConnected {
                print("イヤホンが解除されました。")
            }

        default: break
        }
    }
}

struct ContentView: View {
    @ObservedObject var audioSessionManager = AudioSessionManager()

    var body: some View {
        VStack {
            Text(audioSessionManager.headphonesConnected ? "イヤホンが接続されています。" : "イヤホンが接続されていません。")
        }
    }
}

終わりに

これでオーディオの出力先が変更された場合に検知することができます。

参考文献

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?