if else声明有2个声音

时间:2017-10-24 02:26:41

标签: ios iphone swift

尝试在此处构建此代码,但它的进展如此之好...... 有两个声音文件,当满足Bool状态时每个都会播放....但只有一个声音播放而另一个声音不播放!我在else语句中的错误在哪里?

 func answersSound (answerPickedSound: Bool) {
    if answerPickedSound  {
        if let soundURL = Bundle.main.url(forResource: "Rbeep-02", withExtension: "mp3") {
            do { player = try AVAudioPlayer(contentsOf: soundURL)
                player.play()
            } catch {
                print("Right")
            }
        } else  {
           if let soundURL = Bundle.main.url(forResource: "Wbeep-03", withExtension: "mp3") {
                do { player = try AVAudioPlayer(contentsOf: soundURL)
                    player.play()
                } catch {
                    print("Wrong!")
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

似乎你把第二个声音放错了地方

试试这个

func answersSound (answerPickedSound: Bool) {
    if answerPickedSound  {
        if let soundURL = Bundle.main.url(forResource: "Rbeep-02", withExtension: "mp3") {
            do { player = try AVAudioPlayer(contentsOf: soundURL)
                player.play()
            } catch {
                print("Right")
            }
        }
    }else{
        if let soundURL = Bundle.main.url(forResource: "Wbeep-03", withExtension: "mp3") {
                do { player = try AVAudioPlayer(contentsOf: soundURL)
                    player.play()
                } catch {
                    print("Wrong!")
                }
        }
    }
}

===== EDIT =====

我的建议是使代码更易读和易于调试

//leave this method as is, but move additional code in separated method
func answersSound (answerPickedSound: Bool) {
    //now check boolean and play proper sound
    if answerPickedSound  {
        playSound(name: "Rbeep-02")
    }else{
        playSound(name: "Wbeep-03")
    }

    //Or
    //Use ternary operator
    let soundName = answerPickedSound ? "Rbeep-02" : "Wbeep-03"
    playSound(name: soundName)
}

func playSound(name: String) {
   //use guard else statement to check the sound in bundle
   guard let soundURL = Bundle.main.url(forResource: name, withExtension: "mp3") else {
       print("No sound in bundle for name: \(name)")
       return
   }

   do { 
        player = try AVAudioPlayer(contentsOf: soundURL)
        player.play()
   } catch {
        print("Error playing sound for name: \(name)")
   }
}