我使用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.