我对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后出现以下错误:
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 }