I just started to learning Swift and,I'm trying to add a song into my code to play it when i press the button but that error shows up. how to fix this error?
var buttonAudioPlayer = AVAudioPlayer()
@IBAction func btnWarning(sender: UIButton) {
play()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func play() {
let buttonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("warning", ofType: "mp3")!)
let one = 1
if one == 1 {
buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL) //getting the error in this line
buttonAudioPlayer.prepareToPlay()
buttonAudioPlayer.play()
}
}
The compiler correctly tells you that the initializer can throw an error as the method declaration correctly states (e.g. when the NSURL
does not exist):
init(contentsOfURL url: NSURL) throws
Therefore you as the developer have to handle an eventually occuring error:
do {
let buttonAudioPlayer = try AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch let error {
print("error occured \(error)")
}
Alternatively you can tell the compiler that the call will actually always succeed via
let buttonAudioPlayer = try! AVAudioPlayer(contentsOfURL: buttonAudioURL)
But that will cause your app to crash if the creation actually does not succeed - be careful. You only should use the second approach if you are trying to load app resources that have to be there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With