如何在iOS应用程序中使用Swift 2音频?

我使用SpriteKit和 Swift在Xcode 7测试版上制作了一个游戏,我试图把Audio放在它里面,但是它不是可以使用的,因为Xcode发现了3个错误,我是初学者,我不知道如何解决它们.
import AVFoundation

    var audioPlayer = AVAudioPlayer()


    func playAudio() {
        // Set the sound file name & extension
        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Flip 02",ofType: "wav")!)

        // Preperation
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,error: nil)
        AVAudioSession.sharedInstance().setActive(true,error: nil)

        // Play the sound
        var error: NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound,error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
}

代码错误在这里:

代码1:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,error: nil)

错误1:

Extra argument ‘error’ in call

代码2:

AVAudioSession.sharedInstance().setActive(true,error: nil)

错误2:

Extra argument ‘error’ in call

代码3:

audioPlayer = AVAudioPlayer(contentsOfURL: alertSound,error: &error)

错误3:

Cannot find an initializer for type ‘AVAudioPlayer’ that accepts an argument list of type ‘(contentsOfURL: NSURL,error: inout NSError?)’

你的贡献可能会帮助我.谢谢.

解决方法

使用内部的功能捕捉和使用尝试的投掷:
var audioPlayer = AVAudioPlayer()

func playAudio() {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource("Flip 02",ofType: "wav") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
    } catch {
        print(error)
    }
}

有关完整的Swift 2错误处理说明,请参见this answer.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...