2017-07-24 22 views
0

我有这个错误在那里我用avfoundation做出路径到我的音频文件,所以,当我使用这行代码不能解开值时使用代码的这一行具体

audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Alone", ofType: "m4r")!)) 
audioPlayer.prepareToPlay() 

经常死机。并给我

fatal error: unexpectedly found nil while unwrapping an Optional value 

我拥有所有代码,因为编译器没有显示任何错误。 我使用的Xcode 9快捷4

+1

它没有通过“Alone.m4r”资源获取URL路径。所以,它会崩溃。 –

+0

如果你尝试,你应该抓住一样好,甚至让它崩溃 –

+0

问题可能是由于您使用的是在强制展开:Bundle.main.path(forResource:“当家”,ofType:“M4R”)! – PGDev

回答

2

这会发生,因为你不得不不存在的路径展开。通常这是一个不好的做法。尽量避免强行解包。 试试这个:如果你看到在调试控制台中的“错误的道路”,这意味着与文件名“当家”和延伸“M4R”资源

guard let path = Bundle.main.path(forResource: "Alone", ofType: "m4r") else { 
    print("wrong path") 
    return 
} 
let url = URL(fileURLWithPath: path) 
audioPlayer = try AVAudioPlayer(contentsOf: url) 
audioPlayer.prepareToPlay() 

那么不会在你的应用程序包存在。 希望得到这个帮助。