我试图加载音频被设置到viewDidLoad中函数内部不同的按钮。然而,我的应用程序崩溃与此错误:
主题1:致命错误:意外发现零而展开的可选值
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")
}
}
的注释功能构建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 = ["","","","","","","","","","","","","","","","","","","","","","","",""]
这是因为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")
}
}
}
看看哪些关键是不是在玩。