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:
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 //if I type 'let soundName = "1" or Hard code the value' - it will work fine
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") // - This is always printed when I use the variable result from the switch
}
}
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.
Added More Information Here: https://forums.developer.apple.com/message/137380#137380
playSound(condition:)
is being called. – AlexanderplaySound(condition:)
function? – Alexander