延迟播放阵列中的声音

play sounds in array with delay

我正在尝试播放数组中的声音,中间有时间延迟。

我已经尝试了从 while 循环到使用下面的延迟函数的所有方法,似乎没有任何效果。

代码仅播放数组中的前两个字符串,然后停止。

请帮助我):

var audioPlayer : AVAudioPlayer!
var selectedSoundFileName : String = ""
var n : Int = 0

// array containing the sound files 
let playArray = ["base","snare","base","base","snare"]

// Button Press to start play sequence 

@IBAction func playSequence(_ sender: Any) {

    selectedSoundFileName =playArray[0]
    playSound()  

    let when = DispatchTime.now() + 1
    DispatchQueue.main.asyncAfter(deadline: when) {
        selectedSoundFileName =playArray[1]
        playSound()
    }
    let when = DispatchTime.now() + 1
    DispatchQueue.main.asyncAfter(deadline: when) {
        selectedSoundFileName =playArray[2]
        playSound()
    }
}

func playSound() {
    let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "mp3")
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    } catch {
        print(error)
    }
    audioPlayer.play()
}

文件 playArray[1]playArray[2] 计划同时播放,因为您的两个 when 值相同。只有 DispatchQueue.main.asyncAfter 中的块在延迟之后运行,而不是后续代码。尝试以下操作:

@IBAction func playSequence(_ sender: Any) {

 selectedSoundFileName =playArray[0]
 playSound()  

 let when = DispatchTime.now() + 1
 DispatchQueue.main.asyncAfter(deadline: when) {
     selectedSoundFileName =playArray[1]
     playSound()
     let nextWhen = DispatchTime.now() + 1
     DispatchQueue.main.asyncAfter(deadline: nextWhen) {
        selectedSoundFileName =playArray[2]
        playSound()
     }
 }
}

编辑:
以下代码将更具可扩展性。

@IBAction func playSequence(_ sender: Any) {
    for index in 0..<playArray.count{
        let when = DispatchTime.now() + Double(index)//The sounds won't overlap as long as each sound's duration is 1 sec. If not you may have to add the duration of each sound to the delay instead of just a second.
        DispatchQueue.main.asyncAfter(deadline: when) {
          selectedSoundFileName = playArray[index]
          playSound()
        }
    }
}