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

macOS BigSur下UNUserNotificationCenter自定义通知音效无法播放

解决方案

核心代码错误修正

你的代码存在两处直接导致自定义音效不生效的逻辑问题:

  • 创建自定义UNNotificationSound实例后没有赋值给content.sound属性
  • 后续显式将content.sound设置为了系统默认的.defaultCritical,完全覆盖了自定义音效的配置

修正后的代码如下:

private func showNotification(title: String, subtitle: String) {
    let content = UNMutableNotificationContent()
    content.title = title
    content.subtitle = subtitle

    // 文件在Bundle根目录直接传入对应文件名即可
    content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "one.caf"))
    
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request)
}

额外检查项(修正代码后仍不生效可逐一排查)

  • 音效文件合规检查:通知自定义音效时长不能超过30秒,超出后系统会自动 fallback 到默认音效;编码推荐使用线性PCM、IMA4格式的caf、wav文件
  • 前台播放配置:如果需要应用在前台活跃状态下也能播放通知音效,需要实现UNUserNotificationCenterDelegate协议的对应方法:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.banner, .sound, .badge])
}
  • 权限配置检查:申请通知权限时必须包含.sound选项,否则所有通知音效都无法正常播放:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    // 处理权限申请结果
}
  • 文件名匹配检查:确保代码中传入的文件名、后缀、大小写和实际文件完全一致,避免大小写不匹配导致资源加载失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 09:06:04