【问题标题】:Swift ERROR : : Call can throw, but it is not marked with 'try' and the error is not handled [duplicate]Swift ERROR ::调用可以抛出,但它没有用'try'标记并且错误没有被处理[重复]
【发布时间】:2015-12-21 13:08:06
【问题描述】:

我刚开始学习 Swift,我正在尝试在我的代码中添加一首歌曲以在我按下按钮时播放它,但出现了该错误。如何解决此错误?

var buttonAudioPlayer = AVAudioPlayer()

@IBAction func btnWarning(sender: UIButton) {
    play()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

func play() {
    let buttonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("warning", ofType: "mp3")!)
    let one = 1

    if one == 1 {
        buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL) //getting the error in this line
        buttonAudioPlayer.prepareToPlay()
        buttonAudioPlayer.play()
    }
}

【问题讨论】:

  • “相关”部分有9个标题相同的问题。你确定你的问题以前没有被问过和回答吗?
  • 对不起,我还没看到。

标签: ios swift avfoundation


【解决方案1】:

编译器正确地告诉您初始化程序可以抛出错误,因为 method declaration 正确状态(例如,当 NSURL 不存在时):

init(contentsOfURL url: NSURL) throws

因此,作为开发人员,您必须处理最终发生的错误:

do {
    let buttonAudioPlayer = try AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch let error {
    print("error occured \(error)")
}

或者你可以告诉编译器调用实际上总是会成功

let buttonAudioPlayer = try! AVAudioPlayer(contentsOfURL: buttonAudioURL)

但这会导致您的应用程序崩溃如果创建实际上没有成功 - 请小心。仅当您尝试加载 必须 存在的应用资源时,才应使用第二种方法。

【讨论】:

  • 感谢您的帮助!他们都是正确的,但现在我听不到任何声音,我在那里有一个名为“warning.mp3”的文件我试图将 buttonAudioPlayer.play() 放在覆盖 func 但没有用,我也试图把它放在我的创造了乐趣,也没有工作,我应该把这个放在哪里?
  • @CemAtes 如果您有第二个问题,请将其作为单独的问题发布 - 这个答案和问题是关于潜在错误,而不是关于播放器最终没有播放文件:) 请接受在这里找到答案,尝试找出解决当前问题的方法,如果找不到,请发布新问题。
  • 我只是以某种方式修复了大声笑。再次感谢! :)
【解决方案2】:

AVAudioPlayer(contentsOfURL: buttonAudioURL) 有可能抛出异常。所以需要添加异常处理代码。

 do {
        try buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL)
    } catch {
        //handle exception here
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2016-01-24
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多