Ios Swift ERROR::调用可以抛出,但未标记为';试试';并且错误没有得到处理
我刚开始学习Swift,我试图在我的代码中添加一首歌曲,当我按下按钮时播放,但出现了错误。如何修复此错误Ios Swift ERROR::调用可以抛出,但未标记为';试试';并且错误没有得到处理,ios,swift,avfoundation,Ios,Swift,Avfoundation,我刚开始学习Swift,我试图在我的代码中添加一首歌曲,当我按下按钮时播放,但出现了错误。如何修复此错误 var buttonAudioPlayer = AVAudioPlayer() @IBAction func btnWarning(sender: UIButton) { play() } override func viewDidLoad() { super.viewDidLoad() } func play() { let buttonAudioURL =
var buttonAudioPlayer = AVAudioPlayer()
@IBAction func btnWarning(sender: UIButton) {
play()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func play() {
let buttonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("warning", ofType: "mp3")!)
let one = 1
if one == 1 {
buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL) //getting the error in this line
buttonAudioPlayer.prepareToPlay()
buttonAudioPlayer.play()
}
}
编译器正确地告诉您,初始值设定项可以在正确状态下抛出错误(例如,
NSURL
不存在时):
因此,作为开发人员,您必须处理最终发生的错误:
do {
let buttonAudioPlayer = try AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch let error {
print("error occured \(error)")
}
或者,您可以告诉编译器,调用实际上总是通过
let buttonAudioPlayer = try! AVAudioPlayer(contentsOfURL: buttonAudioURL)
但如果创建实际上没有成功,这将导致你的应用程序崩溃-小心。只有当您试图加载有的应用程序资源时,才应该使用第二种方法。有可能
AVAudioPlayer(contentsOfURL:buttonAudioURL)
会引发异常。因此,您需要添加异常处理程序代码
do {
try buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch {
//handle exception here
}
“相关”部分有9个标题相同的问题。你确定你的问题以前没有被问过和回答过吗?对不起,我没有看到。谢谢你的帮助!它们都是正确的,但现在我听不到任何声音,我在那里有一个文件叫“warning.mp3”,我试图在override func中放入buttonAudioPlayer.play(),但不起作用,我也试图将其放入我创建的fun中,但也不起作用,我应该把它放在哪里?@CemAtes如果你还有第二个问题,请将其作为一个单独的问题发布-此答案和问题是关于潜在错误的,而不是关于最终未播放文件的玩家:)请在此处接受答案,尝试找出当前问题的解决方案,如果找不到,请发布新问题。我只是以某种方式修复了lol。再次感谢!:)
do {
try buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch {
//handle exception here
}