ios - 如何使用Swift初始化AVAudioPlayer

标签 ios audio swift avaudioplayer

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/

相关文章:

c++ - 树莓派SFML播放音频

ios - 一次选择多个 UITextView

ios - 错误 : Value of type 'AppDelegate?' has no member 'present'

c# - 播放声音,等待它完成然后做点什么?

html - 如何在ios中的UITextview或UIView中显示HTML数据

java - 如何使用Java Midi STOP

iOS - 检查掩码 ip 是否有效(在 ip 范围内)

ios - 当用户离开并返回应用程序时如何防止动画完成

ios - swift : Crashes due to no superview 中的 VFL 约束

android - 在没有互联网的本地 Wi-fi 网络中是否可以进行网络通知?