swift - AVAudioPlayer 即将为零

标签 swift xcode swift3 xcode8 avaudioplayer

我的代码有问题,但我不知道出了什么问题。如果我编译代码,一切都很好,但如果我运行代码,我会收到此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

我见过很多相同的问题,但这些问题的答案对我来说没有用。

import UIKit
import AVFoundation
import AudioToolbox



class ViewController: UIViewController{
   
    var audioPlayer = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath:  Bundle.main.path(forResource: "beep", ofType: "wav")!))
            audioPlayer.prepareToPlay()
            
        } catch{
            print(error)
        }
        
        //standaard klaarmaaklijst
        nummerLabel.text = "\(schijnNummer)"
        nummerCheck()
    }

@IBOutlet weak var nummerLabel: UILabel!
}

我希望有人知道我的代码有什么问题。

最佳答案

swift :

    if let path = Bundle.main.path(forResource: "beep", ofType:"wav") {
        let url = URL(fileURLWithPath: path)

        do {

            let audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()

        } catch{
            print(error)
        }
    }

注意:请检查url是否正确且不为零。

关于swift - AVAudioPlayer 即将为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851393/

相关文章:

swift - 协议(protocol)扩展中的嵌套结构 : Type '...' cannot be nested in generic function '...()'

xcode - 为什么 Xcode 4 持续显示 git 存储库的 "Checking source control status"?

ios - 由于信号 : Segmentation fault: 11 swift 3,命令失败

ios - 用 Swift 模糊 CameraView 中的特定区域?

swift - UIImageJPEGRepresentation 是如何工作的?

iphone - UIScrollView滚动矩形到可见方法

ios - 如何在 Xcode 中为大量现有的 swift 文件和类添加前缀

ios - 使用具有默认委托(delegate)实现的另一个协议(protocol)将委托(delegate)分配给一个类?

ios - 在 NSBatchDeleteRequest 之后使用核心数据

ios - UIWebView 不显示我的网页