Juli IchSelber Juli IchSelber - 2 months ago 20
Swift Question

Music player error

I get an error in the first line of my music player code. How can I fix it?


Error: Call can throw but its not marked with try and the error is not
handled


audioPlayer = AVAudioPlayer(contentsOf: pianoSound as URL)
audioPlayer.prepareToPlay()
var pianoSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "C", ofType: "m4a")!)
var audioPlayer = AVAudioPlayer()

Answer

As it is possible to conclude from the error you get :

Error: Call can throw but its not marked with try and the error is not handled

Because AVAudioPlayer can throw exception you should use do {} catch {}

let path = Bundle.main.path(forResource: "C", ofType:"m4a")!
let url = URL(fileURLWithPath: path)

do {
    let sound = try AVAudioPlayer(contentsOf: url)
    sound.play()
} catch {
    // Catch exception
}

This is example of working prototype:

class ViewController: UIViewController {

    var boomSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "boom", ofType: "wav")!)
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func play(_ sender: AnyObject) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: boomSound as URL)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            // Catch exception
        }

    }
}