Hi guys
I was fumbling around with a project. I tried to implement a dictionary but for some reason I'm not getting any sound (the sound file is where it ought to be). This is a Model class. Can somebody explain me what is going wrong?
Tx once more
ps: what also bothers me is that I had to declare soundDictionary as a [String: AVAudioPlayer]. I would have preferred [String: AVAudioPlayer?] but then I got, of course, nil on the statement
I was fumbling around with a project. I tried to implement a dictionary but for some reason I'm not getting any sound (the sound file is where it ought to be). This is a Model class. Can somebody explain me what is going wrong?
Code:
private var guitarPlayer = AVAudioPlayer()
private var applausePlayer = AVAudioPlayer()
private var monsterPlayer = AVAudioPlayer()
private var bubblesPlayer = AVAudioPlayer()
private let soundDictionary: [String: AVAudioPlayer]
init(){
soundDictionary = ["guitar": guitarPlayer, "applause": applausePlayer, "monster": monsterPlayer, "bubbles": bubblesPlayer]
}
func play(sound: String){
var player = soundDictionary[sound]!
if let url = Bundle.main.url(forResource: sound, withExtension: "wav"){
player = try! AVAudioPlayer(contentsOf: url)
player.play()
}
}
func playGuitarSound() {
// if let url = Bundle.main.url(forResource: "guitar", withExtension: "wav"){
// guitarPlayer = try? AVAudioPlayer(contentsOf: url)
// guitarPlayer?.play()
// }
self.play(sound: "guitar")
}
Tx once more
ps: what also bothers me is that I had to declare soundDictionary as a [String: AVAudioPlayer]. I would have preferred [String: AVAudioPlayer?] but then I got, of course, nil on the statement
Code:
var player = soundDictionary[sound]!