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

问题描述 投票:0回答:1

我正在研究一个旧的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
        }
    }
  1. 获取声音文件的完整路径,并使用NSURL.fileURLWithPath()将其转换为URL。
  2. 调用AVAudioPlayer(contentsOfURL:error :)以在音频播放器中加载声音文件。
  3. 将numberOfLoops设置为零,以便声音根本不会循环。调用prepareToPlay()来预加载该声音的音频缓冲区。
  4. 最后,使用文件名作为字典键,将播放器对象保存在音频字典中。
swift4 avplayer
1个回答
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) }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.