2016-05-10 3 views
0

ここで私が苦労してる非常に奇妙な現象だ:スウィフト2:私は、ファイル名として変数を使用する場合、オーディオファイルのパスを見つけることができません

私はベースのボタンのクリックでオーディオファイルを再生しようとしているが、特定の状況でたとえば、条件 "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

+0

'playSound(condition:)'がどこで呼び出されているかなど、より多くのコードコンテキストを与えてください。 – Alexander

+0

ボタンをクリックすると呼び出されます。条件は何日か、何時何かなどの要素によって異なります。 – zaam

+0

お待ちください。両方の部分を 'playSound(condition:)'関数の一部に貼り付けましたか? – Alexander

答えて

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")?。パス//私が入力した場合 '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 
} 
+0

からsoundNameを使用する場合soundNameは関数の外で宣言されています...たとえ内部に宣言しても、それはまだ動作しません – zaam

関連する問題