以延迟播放阵列中的声音

时间:2017-12-12 23:43:52

标签: swift avaudioplayer

我正在尝试从阵列中播放时间延迟的声音。

我尝试了从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()
}

1 个答案:

答案 0 :(得分:0)

文件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()
        }
    }
}