swift - 尝试播放声音时如何解决 "found nil while unwrapping optional value"错误?

标签 swift xcode audio null optional

我正在制作一个播放声音的功能

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 文件显示在复制包资源中。您可以通过单击您的项目 > 选择您的目标 > 构建阶段 > 复制捆绑资源来找到它。如果您在那里看不到它,请单击加号按钮添加它。
screenshot

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/

相关文章:

audio - 在Phonegap中播放音频不起作用

audio - 使用 ffmpeg、linux 提取音频

ios - Swift4 中的异步 DispatchQueue 和多线程

swift - 无法将类型 'String' 的值转换为预期的参数类型 'UIImage' 。 UIImagePicker放入collectionView - 想在VC中查看详细内容?

ios - Firebase 服务器时间戳和非 64 位设备 : Integer literal '...' overflows when stored into 'Int'

iphone - 将连接更改为 3G 或 EDGE 以测试慢速互联网连接

ios - 从 XIB 调整 UISwitch 的大小

ios - 如何在ios中限制下载时间?

iphone - 如何在 Objective C 中使用 strlen 查找字符串长度

audio - 使用 Google Speech 时从 Google Cloud Storage 访问音频文件