我正在制作一个播放声音的功能
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
})
}
运行我能做的应用程序。但是每当你按下一个按钮时,它就会崩溃并给我这个错误:fatal error :在展开 optional 值时意外发现 nil:文件/Users/administrator/Desktop/Xcode Projects/pianoButtons/pianoButtons/ViewController.swift,第 37 行
optional 值似乎是 url!从我的声音功能。
我已经尽我所能,但没有运气。如何避免此错误并在不崩溃的情况下播放声音?
最佳答案
确保您的 soundName.wave 文件显示在复制包资源中。您可以通过单击您的项目 > 选择您的目标 > 构建阶段 > 复制捆绑资源来找到它。如果您在那里看不到它,请单击加号按钮添加它。
var soundPlayer: AVAudioPlayer?
func playSentSound() {
DispatchQueue.main.async{
let path = Bundle.main.path(forResource: "soundName.mp3", ofType: nil)!
let url = URL(fileURLWithPath: path)
do {
self.soundPlayer = try AVAudioPlayer(contentsOf: url)
print("Playing")
self.soundPlayer?.play()
} catch {
// couldn't load file :(
print("Cant Load File")
}
}
}
关于swift - 尝试播放声音时如何解决 "found nil while unwrapping optional value"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62945496/