You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AVRouteKit实现WatchKit向蓝牙设备共享音频并添加AirPlay按钮

watchOS AVPlayer实现原生AirPlay路由选择功能

要实现和Apple Music一致的AirPlay设备切换效果,直接调用系统原生API即可,无需自定义UI,具体实现步骤如下:

1. 配置音频会话

首先需要提前配置AVAudioSession的类别为播放模式,确保音频路由切换可以正常生效:

import AVFoundation

do {
    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
    try AVAudioSession.sharedInstance().setActive(true)
} catch {
    print("音频会话初始化失败: \(error.localizedDescription)")
}

2. 添加系统原生AirPlay按钮

watchOS 6.0及以上版本提供了AVRoutePickerView控件,点击后会自动弹出系统级的AirPlay设备选择弹窗,效果和Apple Music完全一致:

import AVKit

// 初始化AirPlay选择按钮
let airplayButton = AVRoutePickerView(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
// 自定义按钮配色适配你的UI
airplayButton.tintColor = .accentColor
// 将按钮添加到导航栏或者自定义视图层级中
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: airplayButton)

3. 可选:监听音频路由切换事件

如果需要在用户切换播放设备后执行自定义逻辑,可以监听系统路由变化通知:

// 注册通知
NotificationCenter.default.addObserver(
    self,
    selector: #selector(audioRouteChanged(_:)),
    name: AVAudioSession.routeChangeNotification,
    object: nil
)

@objc private func audioRouteChanged(_ notification: Notification) {
    guard let info = notification.userInfo,
          let reasonRaw = info[AVAudioSessionRouteChangeReasonKey] as? UInt,
          let reason = AVAudioSession.RouteChangeReason(rawValue: reasonRaw) else { return }
    
    switch reason {
    case .newDeviceAvailable:
        // 新音频设备接入时的逻辑
        break
    case .oldDeviceUnavailable:
        // 原有音频设备断开时的逻辑
        break
    default:
        break
    }
}

注意事项:

  • 最低兼容版本为watchOS 6.0,更低版本系统无法使用该原生控件
  • 音频会话必须配置为.playback类别,否则AirPlay切换不会生效
  • 系统原生控件自带的弹窗逻辑无需额外开发,默认支持所有AirPlay、蓝牙音频设备的选择和切换

内容的提问来源于stack exchange,提问作者Muazam Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:24:00