I\'m simply trying to play audio when I tap a button, but I get an error with this line of code.
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL,
The AVAudioPlayer class can throw an error, You need to take this into consideration. I personally prefer a do statement which gives the opportunity to catch and handle the error.
This code worked fine for me:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!)
let ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer.play()
} catch let error {
print("error loading audio: Error: \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You could also make this to an optional, like this:
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer?.play()
Using this method it will only attempt to play the file if no error was thrown in the previous statement, but will prevent a runtime error.
You need to use the new Swift 2 syntax by changing that line to
ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)