2016-10-01 192 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最新的一個 –