简体   繁体   English

如何使用Swift初始化AVAudioPlayer

[英]How to initialize AVAudioPlayer using Swift

I'm creating a game using Swift and SpriteKit in Xcode 6.1 and I can't get AVAudioPlayer to initialize. 我正在Xcode 6.1中使用Swift和SpriteKit创建游戏,但无法获取AVAudioPlayer进行初始化。 I have an SKScene for my menu, and I want to run music in my "Sounds" folder called "menu.mp3." 我的菜单中有一个SKScene,我想在名为“ 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()
}

I put this in my initializer right after my super.init call. 我在super.init调用之后将其放在初始化程序中。 The error I get follows: 我得到的错误如下:

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. 我已经添加了AVFoundation框架并将其导入到此场景,但是它仍然崩溃。 Is there something wrong with my filePath that makes my audioPlayer not initialize or something? 我的filePath出了点问题,导致我的audioPlayer无法初始化吗? 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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM