Here's a very strange phenomenon that I'm struggling with:
I'm trying to play an audio file on a button click based on a certain context. For instance if the condition "A" I'll play a certain sound (on button click) and if it is "B" I'd play another sound. I use a switch statement to decide what sounds are played for which condition.
The problem: Even though I'm getting the conditions to work correctly, the AVAudioPlayer always returns nil. But when I hard-code the file to be played, it works just fine. It is only when I use a variable to decide which sound to be played "in the switch statement" is when the sound doesn't play, else when I use a static variable without changing its value, it works fine.
Here's my code: (It is called when a button is clicked and depending upon a condition such as time or day it will play a certain sound using files I've added)
func playSound(Condition: String){
switch Condition {
case "1":
soundName = "1"
case "2":
soundName = "2"
case "3":
soundName = "3"
case "4":
soundName = "4"
case "5":
soundName = "5"
default:
soundName = "default"
}
let pathString = NSBundle.mainBundle().URLForResource(soundName, withExtension: "m4a")?.path // hardcoding soundName makes it work
if let soundFilePath = pathString {
let sound = NSURL.fileURLWithPath(soundFilePath)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL:sound)
audioPlayer.prepareToPlay() audioPlayer.play()
}catch {
print("Error getting the audio file")
}
} else {
print("Error: Can't find file. Path is nil") /
}
}
Can anyone please help me figure out why? Is the switch taking too long? I doubt because I can print the value of the condition before I play the sound. Thanks in advance.