【问题标题】:Could not find overload for 'PathForResource' when playing audio file播放音频文件时找不到“PathForResource”的重载
【发布时间】:2015-07-06 22:33:50
【问题描述】:

我有一个在 Xcode6 中运行良好的 Swift 文件。当我升级到 Xcode7 时,我现在收到一个阻止程序编译的错误。下面是不起作用的代码 sn-p。我收到的错误只是指出“找不到接受提供的参数的 'PathForResource' 的重载。”

func playRecord(sender:UITapGestureRecognizer){

    var tag = sender.view!.tag
    let sound:NSURL

    switch tag{

    case 0: // red
    sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!

    case 1: // blue
        sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("blue", ofType: "wav")!)!

    case 2: // white
    sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("white", ofType: "wav")!)!


    default:
    sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!

    }
    do {
        audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
    } catch _ {
        audioPlayer = nil
    }
    audioPlayer.prepareToPlay()
    audioPlayer.play()


}

【问题讨论】:

  • 这不是对您问题的回答,只是对您提供的代码的评论:您真的不应该在 do 块之外调用 prepareToPlay()play()以您所做的方式,因为如果创建音频播放器失败,它将尝试播放不存在的东西。
  • @TwoStraws 那么您是否建议将这两个调用包装在一个条件中?条件检查 audioPlayer 是否具有良好的价值?
  • 您应该考虑将prepareToPlay()play() 直接移动到try 行的下方。如果try 执行失败,将直接跳转到catch 块,因此不存在执行以下两行的风险。

标签: ios swift swift2 xcode7


【解决方案1】:

Swift 2 的感叹号太多了,因为 fileURLWithPath 现在返回 NSURL 而不是 NSURL?

具体来说,改变这个:

sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)!

到这里:

sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("red", ofType: "wav")!)

...问题应该会消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2020-02-11
    • 2017-08-27
    • 2021-05-19
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多