【问题标题】:AVFoundation play sound swift 2AVFoundation 快速播放声音 2
【发布时间】:2015-09-28 22:47:01
【问题描述】:

我尝试使用 Swift 2.0 播放声音 如果我写 'try' 没有 '!'我有错误 “不处理从这里抛出的错误” 而且 AVAudioPlayer 不是可选的,为什么 Xcode 请求“尝试!” 如果我写“试试!”我的应用程序崩溃 “在展开可选值时意外发现 nil”

class TouchViewController: UIViewController {
var soundPath:NSURL? 
...................
 //Play Bipsound
        do { soundPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Bipsound", ofType: "wav")!)
           var sound = try! AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil)
            sound.prepareToPlay()
            sound.play() }

【问题讨论】:

    标签: ios swift avfoundation


    【解决方案1】:

    假设您以前从未在 Swift 中看到过 ! 强制展开运算符并完全停止使用它。它基本上是“如果此可选选项包含 nil 则崩溃”运算符。使用@LLooggaann 在他的优秀答案中概述的“if let”样式可选绑定或尝试/捕获。 (已投票)

    【讨论】:

    • 同意。我确实在soundPath 上使用了它,但只是因为我 100% 知道从上面的行来看它是安全的,而且我假设它被声明为可选是有原因的。总是可以多加一个if let 以确保超级安全。
    【解决方案2】:
        var soundPath:NSURL? 
    
        if let path = Bundle.main.path(forResource: "Bipsound", ofType: "wav") {
            soundPath = NSURL(fileURLWithPath: path)
            do {
                let sound = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint:nil)
                sound.prepareToPlay()
                sound.play()
            } catch {
                //Handle the error
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多