import Foundation //Needed for dispatch_once_timport AVFoundation //Needed to play soundsclass 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后出现以下错误:
Value of optional type ‘AVAudioPLayer?’ not unwrapped; dID you mean to use ‘!’ or ‘?’?
但是,在使用建议的修复程序时,它告诉我删除刚刚添加的感叹号.这里的确切问题是什么?
解决方法 试试用?如您所愿,您的歌曲变量必须是可选的: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”:
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}总结
以上是内存溢出为你收集整理的ios – “尝试?”和AVAudioPlayer的问题全部内容,希望文章能够帮你解决ios – “尝试?”和AVAudioPlayer的问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)