I'm creating a game using Swift and SpriteKit in Xcode 6.1 and I can't get AVAudioPlayer to initialize. I have an SKScene for my menu, and I want to run music in my "Sounds" folder called "menu.mp3." However, it crashes every time I run my game. My code is below:
let filePath:NSURL = NSURL(fileURLWithPath: "menu.mp3")!
var er:NSError?
let audioPlayer:AVAudioPlayer = AVAudioPlayer(contentsOfURL: filePath, error: &er)
if (er != nil) {
} else {
audioPlayer.play()
}
我在super.init调用之后将其放在初始化程序中。我得到的错误如下:
fatal error: unexpectedly found nil while unwrapping an Optional value
I've tried a lot of fixes, but I can't figure out what's going wrong. I've added the AVFoundation framework and imported it to this scene, but it continues to crash. Is there something wrong with my filePath that makes my audioPlayer not initialize or something? I've tried switching to other ways and making different parts optional, but I can't get it to work. Thanks!
最佳答案
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
func preparePlayer(name:String){
var error:NSError?
let fileUrl = documentsUrl.URLByAppendingPathComponent(name)
// or
// let fileUrl = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent(name)
let audioPlayer = AVAudioPlayer(contentsOfURL: fileUrl, error: &error)
if error == nil {
audioPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
preparePlayer("menu.mp3")
}
关于ios - 如何使用Swift初始化AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868763/