使用Swift播放系统声音

时间:2014-10-27 09:02:44

标签: ios swift system-sounds

我在使用系统声音按下按钮时尝试播放声音。我一直收到错误:"致命错误:在打开一个可选值"时意外地发现了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 个答案:

答案 0 :(得分:2)

我认为正确的方法是在第三个参数中使用filetype:

    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

答案 1 :(得分:2)

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

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

}

答案 2 :(得分:0)

Swift 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)

答案 3 :(得分:0)

Swift 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!")
}