ios - Swift 2.2 错误处理和音频

标签 ios swift error-handling

我正在学习 swift 1.0 的教程(偶然),它展示了如何播放声音。现在在 swift 2.0 中它不会工作请帮助。

import UIKit
import AVFoundation

class ViewController: UIViewController {



var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cow", ofType: "wav")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
    super.viewDidLoad()
    ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func playAudio(sender: AnyObject) {
    ButtonAudioPlayer.play();
}

@IBAction func Stop(sender: AnyObject) {
}

最佳答案

使用 do-catch 语句通过运行一段代码来处理错误 ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL)

//ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
do {
    ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL)
} catch let error as NSError {
    print(error.localizedDescription)
}

关于ios - Swift 2.2 错误处理和音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966097/

相关文章:

ios - 将导航栏后退按钮标题重置为默认 iOS

ios - 消除本地类与 Firebase 重命名类的歧义

python - 是否可以更改 fastAPI 中的 pydantic 错误消息?

ios - 添加约束使应用程序崩溃

android - Firebase 拉取通知

ios - 在我以编程方式实例化的 UITextView(使用 NSTextContainer 初始化)中,.text 属性始终为 nil

swift - 更改项目名称后,Apple Mach-O 链接器错误

swift - BLE 在 ESP32 和 Iphone 之间发送字符串

ios - 如何设置 UICollectionViewCell 大小?

R:如何找到应用产生错误的地方