“尝试?”的问题和 AVAudioPlayer
Posted
技术标签:
【中文标题】“尝试?”的问题和 AVAudioPlayer【英文标题】:Issue with "try?" and AVAudioPlayer 【发布时间】:2015-09-27 06:16:13 【问题描述】:我在使用 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?' 的值未拆封;你的意思是用'!'还是“?”?
但是,在使用建议的修复程序时,它告诉我删除刚刚添加的感叹号。这里的确切问题是什么?
【问题讨论】:
【参考方案1】:要按照您的预期使用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
要不使其成为可选,您可以在do catch
中使用try
:
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
【讨论】:
很好的答案 - 非常彻底。顺便说一句,NSError
的强制转换是不必要的:catch print(error)
将给出相同的输出。
非常感谢。更新了答案,因为演员阵容确实是不必要的。以上是关于“尝试?”的问题和 AVAudioPlayer的主要内容,如果未能解决你的问题,请参考以下文章
这种创建和填充 NSMutableArray 的尝试有啥问题?