2

当使用系统声音按下按钮时,我正在尝试播放声音。我不断收到错误消息:“致命错误:在展开可选值时意外发现 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)
4

4 回答 4

2

为了扩展汤姆的答案(这是完全正确的),这里有一个更强大的错误处理程序(这将有助于平息苹果的应用程序测试人员)

else {
        let networkIssueController = UIAlertController(title: "Error", message: "Unable to find an audio file!", preferredStyle: .Alert)
        let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
        networkIssueController.addAction(okButton)

        let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
        networkIssueController.addAction(cancelButton)

        self.presentViewController(networkIssueController, animated: true, completion: nil)// you have to display the alert after you create it

}

于 2015-02-12T19:20:41.857 回答
2

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

    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

于 2014-10-27T09:18:37.550 回答
0

斯威夫特 2.0

func createSystemSoundID() -> SystemSoundID {
    var soundID: SystemSoundID = 0
    let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "roar", "aiff", nil)
    AudioServicesCreateSystemSoundID(soundURL, &soundID)
    return soundID
}

创建一次:

let systemSoundID = createSystemSoundID()

随意调用:

AudioServicesPlaySystemSound(systemSoundID)
于 2016-02-02T03:24:57.627 回答
0

斯威夫特 4.1

if let path = Bundle.main.path(forResource: "roar", ofType: "aif") {
    let url = URL(fileURLWithPath: path) as CFURL
    var soundID: SystemSoundID = 0
    AudioServicesCreateSystemSoundID(url, &soundID)
    AudioServicesPlaySystemSound(soundID)
} else {
    print("file not found!")
}
于 2018-08-24T09:29:47.957 回答