我正在研究一个旧的Swift教程(Swift 2.0),该教程发布在Ray Wenderlich的网站(https://www.raywenderlich.com/2185-how-to-make-a-letter-word-game-with-uikit-and-swift-part-3-3)上,当我试图在Swift 4.2中重新设置一个名为“preloadAudioEffects”的函数时,我遇到了一个错误。错误? appendingPathComponent'不可用:改为在URL上使用appendingPathComponent。
我试图重命名旧的Swift代码[例如:NSBundle为Bundle,stringByAppendingPathComponent为appendingPathComponent()],但由于我对Swift缺乏经验,我仍然遇到一些语法问题。
这是原始代码:
func preloadAudioEffects(effectFileNames:[String]) {
for effect in AudioEffectFiles {
//1 get the file path URL
let soundPath = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent(effect)
let soundURL = NSURL.fileURLWithPath(soundPath)
//2 load the file contents
var loadError:NSError?
let player = AVAudioPlayer(contentsOfURL: soundURL, error: &loadError)
assert(loadError == nil, "Load sound failed")
//3 prepare the play
player.numberOfLoops = 0
player.prepareToPlay()
//4 add to the audio dictionary
audio[effect] = player
}
}
这就是我通过遵循Xcode中的建议尝试做的事情:
func preloadAudioEffects(effectFileNames:[String]) {
for effect in AudioEffectFiles {
//1 get the file path URL
let soundPath = Bundle.main.resourcePath!.appendingPathComponent(effect)
let soundURL = NSURL.fileURL(withPath: soundPath)
//2 load the file contents
var loadError:NSError?
let player = AVAudioPlayer(contentsOfURL: soundURL, error: &loadError)
assert(loadError == nil, "Load sound failed")
//3 prepare the play
player.numberOfLoops = 0
player.prepareToPlay()
//4 add to the audio dictionary
audio[effect] = player
}
}
用resourcePath
替换resourceURL
let soundURL = Bundle.main.resourceURL!.appendingPathComponent(effect)
你必须将AVAudioPlayer
初始化器包装在try
块中
func preloadAudioEffects(effectFileNames:[String]) {
for effect in AudioEffectFiles {
let soundURL = Bundle.main.resourceURL!.appendingPathComponent(effect)
//2 load the file contents
do {
let player = try AVAudioPlayer(contentsOf: soundURL)
//3 prepare the play
player.numberOfLoops = 0
player.prepareToPlay()
//4 add to the audio dictionary
audio[effect] = player
} catch { print(error) }
}
}