2014-10-27 240 views
2

我试图在使用系统声音按下按钮时播放声音。我不断收到错误:“致命错误:意外地发现零,同时解开一个可选值”。我尝试过调试,并且我认为错误发生在var ref行。 “roar.aif”是我的项目中包含的自定义声音。这只是一个半秒。我会很感激的建议。谢谢!使用Swift播放系统声音

 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) 

回答

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

+0

这个工作......之类的。它打印出它找不到声音文件,虽然我的声音文件在我的项目导航器中显示为roar.aif ...任何想法? – user3353890 2014-10-27 09:49:17

+1

检查您的目标的“构建阶段”。在“复制软件包资源”部分中,该文件roar.aif应该存在。 – Tom 2014-10-27 10:10:33

+0

修好了!非常感谢!你一直是一个巨大的帮助! – user3353890 2014-10-27 10:19:06

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 

}

+0

真棒,谢谢! – user3353890 2015-02-12 21:45:12

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)