-3
我對此很新,並試圖找出正確的格式來解決標題中的錯誤。我得到了:let audioPath = NSBundle.mainBundle()。pathForResource(「Pugs.m4a」,ofType:nil)!錯誤:致命錯誤:意外地發現零,同時展開一個可選值
我知道我必須錯過一些東西,只是不知道在哪裏。
進口的UIKit 進口AVFoundation
類的ViewController:UIViewController的{
@IBOutlet var playButton: UIButton!
var playPug = 1
var player: AVAudioPlayer!
@IBAction func playPressed(sender: AnyObject) {
let audioPath = NSBundle.mainBundle().pathForResource("Pugs.m4a", ofType: nil)!
let url = NSURL(fileURLWithPath: audioPath)
do {
if playPug == 1 {
let sound = try AVAudioPlayer(contentsOfURL: url)
player = sound
sound.play()
playPug = 2
playButton.setImage(UIImage(named:"pause_Icon.png"),forState:UIControlState.Normal)
} else {
player.pause()
playPug = 1
playButton.setImage(UIImage(named:"play_Icon.png"),forState:UIControlState.Normal)
}
} catch {
print(error)
}
}
如果你看Apple的文檔,你會看到這個方法是'init(contentsOfURL url:NSURL)',並且使用了Swift 2錯誤處理。文檔應始終是您的第一個地方。鏈接到'AVAudioPlayer'文檔:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/#//apple_ref/occ/instm/AVAudioPlayer/initWithContentsOfURL:error:。鏈接到Swift錯誤處理文檔:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html –
謝謝,我看到了init(contentsOfURL url:NSURL)方法的例子。我仍然不確定如何改變它。我從來沒有見過「扔」前.. – Lou
SO是不是一個教程的好地方。我建議你做一個關於Swift錯誤處理的教程的互聯網搜索。例如:https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch –