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

使用SimplyCoreAudio切换设备时钟源后ID未更新的问题

使用SimplyCoreAudio切换设备时钟源的疑问

我正在使用SimplyCoreAudio切换设备时钟源,代码如下:

debugPrint("nullAudioDevice.clockSourceID \(nullAudioDevice.clockSourceID)")
if let cid = hardwareDevice.clockSourceID {
    if nullAudioDevice.setClockSourceID(cid) {
        debugPrint("hardwareDevice.clockSourceID \(hardwareDevice.clockSourceID)")
        debugPrint("nullAudioDevice.clockSourceID \(nullAudioDevice.clockSourceID)")
    } else {
        debugPrint("false")
    }
}

打印结果如下:

nullAudioDevice.clockSourceID Optional(4294967295)
hardwareDevice.clockSourceID Optional(690487296)
nullAudioDevice.clockSourceID Optional(4294967295)

为何调用setClockSourceID返回成功后,nullAudioDevice的时钟源ID仍为原值?这是否意味着设置未生效?有没有正确的时钟源设置同步方法?


问题分析与解决方案

1. 缓存未即时刷新

SimplyCoreAudio的clockSourceID属性内部可能使用了缓存机制,调用setClockSourceID后不会自动同步硬件的最新状态。解决方法是主动调用设备的refresh()方法强制刷新:

if nullAudioDevice.setClockSourceID(cid) {
    nullAudioDevice.refresh() // 刷新设备属性缓存
    debugPrint("刷新后clockSourceID: \(nullAudioDevice.clockSourceID)")
}

2. 设备硬件/权限限制

  • 检查时钟源兼容性:先通过nullAudioDevice.clockSources获取设备支持的所有时钟源列表,确认你传入的cid在列表中,部分设备不允许跨类型时钟源切换
  • 设备活跃状态:有些音频设备仅在有音频流运行时才能切换时钟源,可尝试先启动一个空的音频流再执行切换操作
  • 系统权限:macOS下需确保应用已获得"音频输入/输出"权限,可在系统设置→隐私与安全性中检查

3. 异步状态更新机制

Core Audio的设备状态更新是异步的,setClockSourceID返回true仅表示请求已提交,硬件可能还未完成切换。可通过监听设备属性变化通知获取最终状态:

// 注册时钟源属性变化通知
NotificationCenter.default.addObserver(
    forName: .AudioDevicePropertyChanged,
    object: nullAudioDevice,
    queue: DispatchQueue.main
) { notification in
    guard let propID = notification.userInfo?[kAudioDevicePropertyIDKey] as? AudioObjectPropertyID else { return }
    if propID == kAudioDevicePropertyClockSource {
        debugPrint("时钟源已更新: \(nullAudioDevice.clockSourceID)")
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:43:16