如何修复'appendingPathComponent'不可用:URL错误时使用appendingPathComponent

时间:2019-04-13 19:38:42

标签: swift4 avplayer

我正在制作一个旧的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
        }
    }
  1. 获取声音文件的完整路径,并使用NSURL.fileURLWithPath()将其转换为URL。
  2. 调用AVAudioPlayer(contentsOfURL:error :)将声音文件加载到音频播放器中。
  3. 将numberOfLoops设置为零,以使声音完全不会循环。调用prepareToPlay()以预加载该声音的音频缓冲区。
  4. 最后,使用文件名作为字典键,将播放器对象保存在音频字典中。

1 个答案:

答案 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) }
    }
}