问题
Trying to play audio but keep receiving fatal error:
unexpectedly found nil while unwrapping an Optional value
Here is my code:
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie", ofType: "mp3"){
var filePathURL = NSURL.fileURLWithPath(filePath)
var audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL!, error: nil)
}else{
println("the filePath is empty")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSlowAudio(sender: UIButton) {
//play sloooowly
audioPlayer.play()
}
}
回答1:
It looks like var filePathURL = NSURL.fileURLWithPath(filePath) is returning nil, wrapped in an Optional. Then on the next line filePathURL! forces the Optional to unwrap, resulting in nil and giving the error you see.
You should check to make sure the filePath is correct for the file you are trying to load. Make sure the file is in your bundle and that you typed the file name correctly. Setting a breakpoint there and debugging would probably be helpful.
Also, to be safer, you may want to change the if statement so NSURL.fileURLWithPath(filePath) is part of the if:
if let filePath = NSBundle.mainBundle().pathForResource("movie", ofType: "mp3"),
let filePathURL = NSURL.fileURLWithPath(filePath) {
var audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL, error: nil)
}else{
println("the filePath is empty OR the file did not load")
}
Also note: I used let instead of var for the variables in the if statement so they are constants. It is good practice to use let when you can.
来源:https://stackoverflow.com/questions/29731358/fatal-error-when-trying-to-play-audio-in-swift