Swift错误:线程1:致命错误:在展开可选值时意外发现nil
我的代码中出现了以下问题:Swift错误:线程1:致命错误:在展开可选值时意外发现nil,swift,optional,unwrap,forced-unwrapping,Swift,Optional,Unwrap,Forced Unwrapping,我的代码中出现了以下问题: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 此消息出现在我的代码的这一行: try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!)) 任何帮助都将不胜感激。提前谢谢 import UIKit import AVFoundation class ViewC
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
此消息出现在我的代码的这一行:
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
任何帮助都将不胜感激。提前谢谢
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if event?.subtype == UIEvent.EventSubtype.motionShake {
let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3")
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
player.play()
} catch {
// process error
}
}
}
}
找不到您的文件 我做了一些小改动来帮助调试和防止崩溃
import UIKit
import AVKit
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if event?.subtype == UIEvent.EventSubtype.motionShake {
if let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3") {
do {
let player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation))
player.play()
} catch (_) {
print("AVAudioPlayer could not play the file.")
}
} else {
print("File was not be found.")
}
}
}
}
这个错误基本上是告诉你
fileLocation
是nil
,而它不应该是这样的。好的,谢谢!那么我该如何解决这个问题呢?@grooveplex我做错什么了吗?你需要确保fileLocation
不是nil
,这可能意味着要确保你试图加载的文件存在-我帮不了你太多,因为我对swift还不是很有经验@grooveplex好,谢谢!谢谢你的帮助!我厌倦了代码,但它一直说“找不到文件”。sound1.mp3在哪里?我把它放在项目的根目录中,它对我有效!嘿,我把它放在根文件夹中,但在另一个名为“声音”的文件夹中,您是否尝试过在文件夹名称前加前缀Bundle.main.path(forResource:“sounds/sound1”,of type:“mp3”)
我已经厌倦了很多次了,但没有任何运气