问题
I am having the following issue with 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
}
}
On the line that assigns the value of the variable "song" in the "prepareAudios" function, I am getting the following error after converting to Swift 2.0:
Value of optional type 'AVAudioPLayer?' not unwrapped; did you mean to use '!' or '?'?
However, upon using the suggested fix, it is telling me to remove the exclamation point I just added. What is the exact issue here?
回答1:
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
}
来源:https://stackoverflow.com/questions/32805153/issue-with-try-and-avaudioplayer