我正在制作一个旧的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)上,当我尝试重新设置一个名为“ preloadAudioEffects”的函数时遇到错误“在Swift 4.2中。错误? 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
}
}
答案 0 :(得分:0)
只需将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) }
}
}