Swift 2: 当我使用变量作为文件名时找不到音频文件路径

Swift 2: Can't find audio file path when I use variables as file names

这是一个我正在努力解决的非常奇怪的现象:

我正在尝试根据特定上下文在单击按钮时播放音频文件。例如,如果条件 "A" 我将播放某种声音(单击按钮时),如果是 "B" 我将播放另一种声音。我使用 switch 语句来决定在什么条件下播放什么声音。

问题:即使我已获得正常工作的条件,AVAudioPlayer 始终 returns 为零。但是当我硬编码要播放的文件时,它工作得很好。只有当我使用一个变量来决定播放哪个声音时 "in the switch statement" 才是声音不播放的时候,否则当我使用一个静态变量而不改变它的值时,它工作正常。

这是我的代码:

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
    }
}

谁能帮我弄清楚为什么?切换时间是否过长?我怀疑是因为我可以在播放声音之前打印条件值。提前致谢。

在此处添加了更多信息:https://forums.developer.apple.com/message/137380#137380

您需要声明声音名称

func playSound(Condition: String){

var soundName: 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 //如果我输入 'let soundName = "1" or Hard code the value' - 它会正常工作

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
}

开始使用了。我想问题出在文件上。重新做了一切,现在它的工作。谢谢你们。