音乐播放器错误

时间:2016-10-01 17:35:48

标签: ios swift xcode

我的音乐播放器代码的第一行出错了。我该如何解决?

  

错误:调用可以抛出,但没有标记为try,错误不是   处理

    audioPlayer = AVAudioPlayer(contentsOf: pianoSound as URL)
    audioPlayer.prepareToPlay()
    var pianoSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "C", ofType: "m4a")!)
    var audioPlayer = AVAudioPlayer()

1 个答案:

答案 0 :(得分:0)

因为可以从错误中得出结论:

  

错误:调用可以抛出,但没有标记为try,错误是   没处理

由于AVAudioPlayer可以抛出异常,因此您应该使用do {} catch {}

let path = Bundle.main.path(forResource: "C", ofType:"m4a")!
let url = URL(fileURLWithPath: path)

do {
    let sound = try AVAudioPlayer(contentsOf: url)
    sound.play()
} catch {
    // Catch exception
}

这是工作原型的例子:

class ViewController: UIViewController {

    var boomSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "boom", ofType: "wav")!)
    var audioPlayer = AVAudioPlayer()

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

    @IBAction func play(_ sender: AnyObject) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: boomSound as URL)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            // Catch exception
        }

    }
}