【问题标题】:How to fix error in AVAudioPlayer init using swift如何使用 swift 修复 AVAudioPlayer init 中的错误
【发布时间】:2014-10-25 20:32:15
【问题描述】:

这是我的代码,正在播放声音,但在我更新到 xcode 6.1 后出现此错误

调用中的额外参数“contentsOfURL”

var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "aiff")!)
//println(alertSound);

// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

var error:NSError?;
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error); // the error
audioPlayer.prepareToPlay();

如何修复错误并让 xcode 停止显示它

【问题讨论】:

    标签: swift xcode6.1


    【解决方案1】:

    在这一行:

    audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
    

    问题是alertSound 现在是一个 Optional,因为NSURL(fileURLWithPath:) 可以返回 nil。你需要打开它:

    audioPlayer = AVAudioPlayer(contentsOfURL: alertSound!, error: &error)
    

    这将允许您的代码编译。但是,最好先明确检查 alertSound 是否为 nil,然后再执行此操作!如果 nil,直接解包会导致崩溃。

    【讨论】:

      【解决方案2】:

      您需要更改 URLForResource 的 pathForResource

      像这样:

      var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().URLForResource("sound", ofType: "aiff")!)
      

      contentsOfURL 需要一个 NSURL 而不是字符串。

      【讨论】:

      • 他打电话给NSURL(fileURLWithPath:)。它需要一个路径字符串,而不是 URL。它制作一个URL,但它采用一个路径字符串。
      猜你喜欢
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多