我尝试使用系统声音按下按钮时播放声音。我不断收到错误消息:“致命错误:在展开可选值时意外发现nil”。我尝试调试,并且我相信错误发生在 var ref 行上。 “roar.aif”是我包含在项目中的自定义声音。它只有一秒半的时间。我将不胜感激建议。谢谢!

        var soundID: SystemSoundID = SystemSoundID()
        var mainBundle: CFBundleRef = CFBundleGetMainBundle()
        var ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, "roar.aif", nil, nil) as CFURLRef!
        println("Here is your ref: \(ref)")
        AudioServicesCreateSystemSoundID(ref, &soundID)
        AudioServicesPlaySystemSound(soundID)

最佳答案

我相信正确的方法是在第三个参数中使用文件类型:

    var soundID: SystemSoundID = 0
    var mainBundle: CFBundleRef = CFBundleGetMainBundle()
    if let ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, CFSTR("roar"), CFSTR("aif"), nil) {
        println("Here is your ref: \(ref)")
        AudioServicesCreateSystemSoundID(ref, &soundID)
        AudioServicesPlaySystemSound(soundID)
    } else {
        println("Could not find sound file")
    }

您确定文件是roar.aif而不是roar.aiff吗?

确保文件不在子目录中,如果是这样,则必须将其添加为第四个参数。

另请:https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFBundleRef/index.html#//apple_ref/c/func/CFBundleCopyResourceURL

关于ios - 使用Swift播放系统声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26584078/

10-12 14:31
查看更多