To use try?
as you intended your song
variable has to be an Optional:
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
}
}
To not make it an Optional, you would use try
inside do catch
:
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)
}
}
Also, if you are absolutely sure that creating the AVAudioPlayer instance will always succeed, you can ignore "do catch" by using try!
:
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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…