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, error: nil)
This is my whole code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Audio File 1", ofType: "mp3")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAudio1(sender: UIButton) {
}
}
The error is
Incorrect argument label in call (have 'contentsOfURL:error:', expected 'contentsOfURL:fileTypeHint:').
When I change error to fileTypeHint, it still does not work.
You need to use the new Swift 2 syntax by changing that line to
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:
You could also make this to an optional, like this:
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.