2016-10-01 180 views
-1

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

Error: Call can throw but its not marked with try and the error is not handled

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

回答

0

由于可以从错误中总结你:

Error: Call can throw but its not marked with try and the error is not handled

因为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 
     } 

    } 
} 
+0

这给我错误的第二行代码 –

+0

什么是错误?什么版本的Xcode? –

+0

我得到Xcode 8最新的一个 –