我正在尝试加载要设置到viewDidLoad函数内不同按钮的音频。但是,我的应用程序崩溃了这个错误:
线程1:致命错误:在展开时出乎意料地发现nil 可选值
override func viewDidLoad() {
annotateKeys()
print(constructedArrayOfNotes)
for key in constructedArrayOfNotes {
let path = Bundle.main.path(forResource: key, ofType: "mp3")
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
player.prepareToPlay()
audioPlayers.append(player)
} catch {
print("error")
}
}
annotate函数构造constructedArrayOfNotes
。
音频文件的名称是“PIANO_C3.mp3”。
这是annotateKeys函数
func annotateKeys() {
for index in 0...11 {
constructedArrayOfNotes[index] = "PIANO_" + arrayOfNotes[index] + String(leftSideOfPiano)
}
for index in 12...23 {
constructedArrayOfNotes[index] = "PIANO_" + arrayOfNotes[index] + String(rightSideOfPiano)
}
}
这就是音频文件的样子:
我不确定我做错了什么,但我猜测路径不正确或Xcode无法找到音频文件。
任何帮助都将不胜感激。
这是更多代码:
var audioPlayers = [AVAudioPlayer]()
var player = AVAudioPlayer()
// An array with notes C through B is sequenced twice in order to
// traverse the left and right keyboard.
let arrayOfNotes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
var constructedArrayOfNotes = ["","","","","","","","","","","","","","","","","","","","","","","",""]
答案 0 :(得分:0)
这是因为path
在某些时候将为零,这意味着您的密钥设置不正确。用这个替换你的功能
for key in constructedArrayOfNotes {
if let path = Bundle.main.path(forResource: key, ofType: "mp3") {
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
player.prepareToPlay()
audioPlayers.append(player)
} catch {
print("error")
}
}
}
看看哪个键没有播放。