问题“尝试?”和AVAudioPlayer

我对AVAudioPlayer有以下问题:

import Foundation //Needed for dispatch_once_t import AVFoundation //Needed to play sounds class PlayStartSong { var song: AVAudioPlayer = AVAudioPlayer() var songStarted: Bool = false class var sharedInstance: PlayStartSong { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: PlayStartSong? = nil } dispatch_once(&Static.onceToken) { Static.instance = PlayStartSong() } return Static.instance! } func prepareAudios() { var path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3") song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!)) //Error Here song.prepareToPlay() song.numberOfLoops = -1 //Makes the song play repeatedly } } 

在“prepareAudios”函数中指定变量“song”的值的行上,转换为Swift 2.0后出现以下错误:

可选类型’AVAudioPLayer?’的值 没有打开; 你的意思是用’!’ 要么 ‘?’?

但是,在使用建议的修复程序时,它告诉我删除刚刚添加的感叹号。 这里的确切问题是什么?

try? 如您所愿,您的song变量必须是可选的:

 class PlayStartSong { var song: AVAudioPlayer? var songStarted: Bool = false class var sharedInstance: PlayStartSong { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: PlayStartSong? = nil } dispatch_once(&Static.onceToken) { Static.instance = PlayStartSong() } return Static.instance! } func prepareAudios() { let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3") song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!)) song?.prepareToPlay() song?.numberOfLoops = -1 //Makes the song play repeatedly } } 

要不使它成为Optional,你可以使用try inside do catch

 func prepareAudios() { do { let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3") song = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!)) song.prepareToPlay() song.numberOfLoops = -1 //Makes the song play repeatedly } catch { print(error) } } 

此外,如果您完全确定创建AVAudioPlayer实例将始终成功,您可以使用try!忽略“do catch” try!

 func prepareAudios() { let path = NSBundle.mainBundle().pathForResource("start-2.0", ofType: "mp3") song = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!)) song.prepareToPlay() song.numberOfLoops = -1 //Makes the song play repeatedly }