如何为UNNotification添加AVFoundation中的iOS系统音效(SystemSoundID)
如何将AVFoundation系统音效用于UNNotification
嘿,这个问题我之前折腾过,其实iOS的UNNotification框架本身不直接支持通过SystemSoundID指定系统音效——因为通知的音效设置只能指向应用包内的音频文件,或者用系统预定义的通知音效(比如UNNotificationSound.default)。不过有个可行的 workaround 能实现你的需求,具体步骤如下:
1. 配置后台音频权限
首先要确保应用在后台/锁屏状态下能播放音效,需要开启后台音频权限:
- 打开Xcode项目的「Signing & Capabilities」面板,添加「Background Modes」能力,勾选「Audio, AirPlay, and Picture in Picture」。
- 或者直接在
Info.plist中添加UIBackgroundModes键,把audio加入到值数组里。
2. 利用通知代理播放系统音效
我们可以在通知触发的回调方法里手动调用AudioServicesPlaySystemSound来播放指定的系统音效,同时不要给通知设置默认或自定义音效(避免双重播放)。
代码示例(Swift)
首先导入AVFoundation:
import AVFoundation
然后在AppDelegate(或者你处理通知的类)中设置UNUserNotificationCenter代理,并实现回调方法:
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 注册通知代理并请求权限 UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge] UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in // 根据需求处理权限申请结果 } return true } // 应用前台收到通知时触发 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 播放指定的系统音效 AudioServicesPlaySystemSound(1016) // 显示通知的alert和badge(按需调整) completionHandler([.alert, .badge]) } // 用户点击通知(后台/锁屏状态)时触发 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 如果需要点击通知时也播放音效,就添加这行 AudioServicesPlaySystemSound(1016) completionHandler() } }
3. 远程推送的额外配置
如果是远程推送,需要在推送payload中加入content-available: 1,这样应用在后台会被短暂唤醒,才能执行播放音效的代码。示例payload:
{ "aps": { "alert": "你的通知内容", "badge": 1, "content-available": 1 } }
注意事项
AudioServicesPlaySystemSound会遵守系统的静音开关,如果需要强制播放,可以考虑使用AVAudioPlayer,但需要额外配置音频会话(比如设置AVAudioSession.Category.playback)。- 不要过度使用这种方式,频繁播放系统音效可能影响用户体验,苹果审核时也会关注这类行为。
- 部分系统音效可能有版权或使用限制,建议选择通用的、无版权风险的音效ID。
内容的提问来源于stack exchange,提问作者alionthego
相关产品推荐
相关产品推荐

