【发布时间】:2018-05-05 09:38:13
【问题描述】:
我正在尝试在应用启动时播放 mp3 文件(5 秒),但我不断收到错误消息:
线程 1:致命错误:在展开可选值时意外发现 nil
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//create SystemSoundID
var soundID:SystemSoundID = 0
let path = Bundle.main.path(forResource: "iPhone100Voice", ofType: "mp3")
let baseURL = NSURL(fileURLWithPath: path!)
AudioServicesCreateSystemSoundID(baseURL, &soundID)
//play
AudioServicesPlaySystemSound(soundID)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
谁能解释一下为什么以及如何解决这个问题?
【问题讨论】:
-
if let path = Bundle.main.path(forResource: "iPhone100Voice", ofType: "mp3"){ }
-
let baseURL = NSURL(fileURLWithPath: path!)- 你应该避免强制解包可选值,即使“相信”它们永远不会 - 相反,你应该始终防范它们并有条件处理不可预见的情况 -
文件
iPhone100Voice.mp3不在捆绑包中。并使用 APIurl(forResource: withExtension:。这避免了创建 URL 的额外步骤。 -
@MadProgrammer 在这种特殊情况下,您应该强制解开可选值,因为崩溃会显示设计错误。如果文件在包中,则代码不能崩溃,因为文件不能在运行时更改。
-
@vadian 然后它留在代码中 - 还有其他选项