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

时间:2016-05-10 17:22:45

标签: ios swift audio avaudioplayer nsurl

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

我正在尝试根据特定上下文按下按钮播放音频文件。例如,如果条件“A”我将播放某种声音(按下按钮),如果它是“B”,我会播放另一种声音。我使用switch语句来决定播放哪种声音的声音。

问题:即使我正在使条件正常工作,AVAudioPlayer也总是返回nil。但是当我对要播放的文件进行硬编码时,它的工作正常。只有当我使用一个变量决定播放哪个声音时“在switch语句中”是声音不播放的时候,否则当我使用静态变量而不改变它的值时,它可以正常工作。

这是我的代码:

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

2 个答案:

答案 0 :(得分:0)

您需要声明soundName

即。

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

让pathString = NSBundle.mainBundle()。URLForResource(soundName,withExtension:“m4a”)?. path //如果我输入'let soundName =“1”或硬编码值' - 它将正常工作

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
}

答案 1 :(得分:0)

让它发挥作用。我想问题出在文件上。重做一切,现在它的工作。多谢你们。