Reputation: 133
I'm trying to load audio to be setup to different buttons inside the viewDidLoad function. However, my app crashes with this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
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")
}
}
The annotate function constructs the array of constructedArrayOfNotes
.
The name of the audio file is "PIANO_C3.mp3".
This is the annotateKeys function
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)
}
}
This is what the audio files look like:
I'm not sure exactly what I'm doing wrong but I'm guessing the path is either not correct or Xcode can't locate the audio file.
Any help would be appreciated.
This is more code:
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 = ["","","","","","","","","","","","","","","","","","","","","","","",""]
Upvotes: 1
Views: 58
Reputation: 234
That is because path
will be nil at some point, which means your keys are not set correctly. Replace your function with this
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")
}
}
}
and see what key is not playing.
Upvotes: 0