Swift - 一系列AVplayers?

时间:2016-02-04 16:20:25

标签: swift

我正在整理一个基于硬编码阵列播放鼓节的应用程序:

var beatArray = [[String]]()

var beat01 = [["kick"], ["snare"], ["kick"], ["snare"]]
var beat02 = [["kick"], ["kick", "snare"], ["kick"], ["kick","snare"]]

根据一组参数,选择beat01或beat02,当按下按钮时,将使用以下选择器启动NSTimer:

    // THIS IS WHAT HAPPENS EVERY BEAT

func increaseCounter() {

    beatCounter++

if beatCounter >= beatArray.count {

    beatCounter = 0

}
    print(beatCounter)




    if beatArray[beatCounter].contains("kick") {

        kickPlayer.currentTime = 0
        kickPlayer.play()

    }

    if beatArray[beatCounter].contains("snare") {

            snarePlayer.currentTime = 0
            snarePlayer.play()


    }

}

kickPlayer和snarePlayer是AVAudioPlayers。 由于只有两种工具,分别声明每个IF语句都没问题,但随着我添加越来越多的工具,这将很快变得混乱。

有没有办法简化这个过程?我正在寻找以下内容:

if beatArray[beatCounter].contains("INSTRUMENT") {

        INSTRUMENTPlayer.currentTime = 0
        INSTRUMENTPlayer.play()

    }

1 个答案:

答案 0 :(得分:2)

将你的玩家放在地图上

let players = ["kick": kickPlayer, "snare": snarePlayer, ...]

然后

for beat in beatArray[beatCounter] {
  if let player = players[beat] {
    player.currentTime = 0
    player.play()
  }
}