"try?" 和 AVAudioPlayer 的问题

Issue with "try?" and AVAudioPlayer

我在使用 AVAudioPlayer 时遇到以下问题:

import Foundation   //Needed for dispatch_once_t
import AVFoundation //Needed to play sounds

class PlayStartSong {

    var song: AVAudioPlayer = AVAudioPlayer()
    var songStarted: Bool = false

    class var sharedInstance: PlayStartSong {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: PlayStartSong? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = PlayStartSong()
        }
        return Static.instance!
    }

    func prepareAudios() {

        var path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3")
        song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))    //Error Here
        song.prepareToPlay()

        song.numberOfLoops = -1 //Makes the song play repeatedly
    }
}

在 "prepareAudios" 函数中为变量 "song" 赋值的那一行,转换为 Swift 2.0 后出现以下错误:

Value of optional type 'AVAudioPLayer?' not unwrapped; did you mean to use '!' or '?'?

但是,在使用建议的修复程序后,它告诉我删除刚刚添加的感叹号。这里的确切问题是什么?

要按预期使用 try?,您的 song 变量必须是可选的:

class PlayStartSong {

    var song: AVAudioPlayer?
    var songStarted: Bool = false

    class var sharedInstance: PlayStartSong {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: PlayStartSong? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = PlayStartSong()
        }
        return Static.instance!
    }

    func prepareAudios() {
        let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3")
        song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
        song?.prepareToPlay()
        song?.numberOfLoops = -1 //Makes the song play repeatedly
    }
}

为了不使其成为可选的,您可以在 do catch:

中使用 try
func prepareAudios() {
    do {
        let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3")
        song = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
        song.prepareToPlay()
        song.numberOfLoops = -1 //Makes the song play repeatedly
    } catch {
        print(error)
    }
}

此外,如果您绝对确定创建 AVAudioPlayer 实例总是会成功,您可以使用 try!:[=18 忽略 "do catch" =]

func prepareAudios() {
    let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3")
    song = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
    song.prepareToPlay()
    song.numberOfLoops = -1 //Makes the song play repeatedly
}