【发布时间】:2020-07-17 00:48:41
【问题描述】:
我正在制作一个播放声音的函数
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
然后在包含我所有按钮的 IBAction 中调用此函数
@IBAction func buttonPiano(_ sender: UIButton) {
playSound(soundName: String(sender.currentTitle!))
sender.backgroundColor = UIColor.white
sender.alpha = 0.3
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300), execute: {
sender.backgroundColor = UIColor.systemBackground
sender.alpha = 1
})
}
运行我能做的应用程序。但是每当你按下一个按钮时,它就会崩溃并给我这个错误:
致命错误:在展开可选值时意外发现 nil:文件 /Users/administrator/Desktop/Xcode Projects/pianoButtons/pianoButtons/ViewController.swift,第 37 行
可选值好像是url!来自我的声音功能。
我已经尽我所能,但没有运气。如何避免此错误并在不崩溃的情况下播放声音?
【问题讨论】:
-
您确定
soundName.wav文件存在吗?检查soundName是什么并检查该文件是否存在。另外,与问题无关但也很重要,you are usingAVAudioPlayerwrongly -
soundName 是一个变量,它获取按下按钮的标题,然后使用该标题查找声音文件(例如,按下 C 按钮应该播放 C.wav)。
-
什么是
ViewController.swift, line 37 -
设置断点,一步一步看nil出现的时候。简单、猜测少、学习曲线最长。
-
当发件人不是 UIButton 或没有标题时,波形文件名将以 nil 结尾。虽然接管可能的按钮看起来很容易 currentTitle 它更安全地询问发件人是否是 UIButton 类以及如果标题为 nil 该怎么办。
标签: swift xcode audio null optional