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

如何在iOS应用中播放设备默认通知音效?替代SystemSoundID方案咨询

播放iOS系统默认通知音效(无需硬编码SystemSoundID)

我明白你的痛点——硬编码SystemSoundID = 1315确实只能播放特定的旧版短信音效,根本不是用户实际设置的系统默认通知音效,而且系统版本更新后这个ID还可能失效。下面给你两种可靠的方法,不用硬编码ID就能播放真正的默认通知音效:

方法一:利用UNNotificationSound获取默认音效(推荐)

UNNotificationSound.default()会自动匹配用户在系统设置里选择的默认通知音效,是最贴合系统行为的方式。你可以获取它的音频URL,再用AVAudioPlayer播放:

import AVFoundation
import UserNotifications

func playDefaultNotificationSound() {
    // 获取系统默认通知音效的URL
    guard let soundURL = UNNotificationSound.default().soundURL else {
        print("无法获取默认通知音效URL")
        return
    }
    
    do {
        // 初始化音频播放器
        let audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch {
        print("播放音效失败:\(error.localizedDescription)")
    }
}

// 调用方法
playDefaultNotificationSound()

方法二:从用户偏好中读取自定义默认音效

如果用户在系统设置里替换了默认通知音效(比如用自己导入的音效),上面的方法依然有效,但你也可以直接从系统偏好中读取音效名称,再拼接路径播放:

import AVFoundation

func playUserPreferredNotificationSound() {
    // 从UserDefaults获取用户设置的默认通知音效名称
    guard let soundName = UserDefaults.standard.string(forKey: "com.apple.preferences.sound.notification.sound") else {
        //  fallback到UNNotificationSound的默认音效
        playDefaultNotificationSound()
        return
    }
    
    var soundURL: URL?
    
    // 首先检查系统内置音效目录
    let systemSoundDir = URL(fileURLWithPath: "/System/Library/Audio/UISounds")
    soundURL = systemSoundDir.appendingPathComponent("\(soundName).caf")
    
    // 如果系统目录没有,检查用户自定义音效目录
    if let url = soundURL, !FileManager.default.fileExists(atPath: url.path) {
        let userSoundDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
            .appendingPathComponent("Sounds")
        soundURL = userSoundDir.appendingPathComponent(soundName)
    }
    
    guard let finalURL = soundURL else {
        print("无法找到指定音效文件")
        return
    }
    
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: finalURL)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch {
        print("播放音效失败:\(error.localizedDescription)")
    }
}

// 调用方法
playUserPreferredNotificationSound()

为什么不推荐硬编码SystemSoundID?

  • 硬编码的ID对应的音效是固定的,不会随用户的系统设置变化,完全不符合“播放默认通知音效”的需求
  • 不同iOS版本中,SystemSoundID的对应关系可能会变更,导致你的App在新版本系统上播放错误的音效甚至失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:19:25