我正在播放存储在iOS应用资产目录中的MP3文件&当我声明播放器具有应用范围的范围时,我声明了我的AVAudioPlayer。我的代码工作正常,但我想知道这是否是不好的做法&如果是这样,为什么。大多数代码示例播放音频声明AVPlayer作为一个可选的,但在声明中没有创建的球员,像这样:是否可以在变量声明中创建AVAudioPlayer()并避免选项/解包?
var audioPlayer: AVAudioPlayer?
我实现低于B/C不必自选任何参考或被迫展开(我我只是在Swift中自己加入,但我将它作为一个早期的“Get Excited”例子,让我的学生们可以在他们的第一个应用程序中播放媒体。希望稍后延迟选项讨论。
//声明AVAudioPlayer并分配一个空的球员
var audioPlayer = AVAudioPlayer()
//调用此函数发挥资产文件的MP3声音名为 “sound0”
func playSound() {
if let sound = NSDataAsset(name: "sound0") {
do {
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.play()
} catch {
print("ERROR: Couldn't create the AVAudioPlayer")
}
} else {
print("ERROR: Couldn't load sound file from asset catalog. Verify file is a valid sound file and that the name is correct.")
}
}
//谢谢!
下面是一个伟大的帖子,更详细地说明了隐式可选项:http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals –
非常感谢。这一切都非常有帮助。并感谢确认的方法是好的! – Gallaugher