Swift: 无法播放基于数组的每个声音序列

Swift: Unable to play each sound sequence based on array

我一直在尝试找出如何使用 switch case 语句根据数组中的值播放一系列声音。到目前为止它只播放最后一个整数对应的声音。

我希望实现的是当我单击“播放”按钮时,它循环遍历每个 soundSeq 数组值并在停止之前播放相应的声音。但在这种情况下,它只播放 tagid 5 的声音。

import UIKit
import AVFoundation

class UIController: UIViewController {
    var audioPlayer : AVAudioPlayer!

    let soundSeq = [2,4,5]

    func playSoundSeq() {
        for tag in soundSeq {
            switch tag {
            case 1 : loopSoundSeq(tagid: tag)
            case 2 : loopSoundSeq(tagid: tag)
            case 3 : loopSoundSeq(tagid: tag)
            case 4 : loopSoundSeq(tagid: tag)
            case 5 : loopSoundSeq(tagid: tag)
            case 6 : loopSoundSeq(tagid: tag)
            case 7 : loopSoundSeq(tagid: tag)
            default : print("no sound played")
            }
        }
    }

    @IBAction func playButton(_ sender: UIButton) {
        playSoundSeq()
    }

    func loopSoundSeq(tagid: Int) {
        var soundURl = Bundle.main.url(forResource: "minisound\(tagid)", withExtension: "wav")

        //machinePlay.append(sender.tag)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURl!)
        }
        catch {
            print(soundURl)
        }

        audioPlayer.play()
    }
}

您需要等待每个声音播放完才能开始下一个。让你的 class 采用 AVAudioPlayerDelegate 并实施 AVAudioPlayerDelegate 方法 audioPlayerDidFinishPlaying(_:successfully:) 并触发序列中的下一个声音:

import UIKit
import AVFoundation

class UIController: UIViewController, AVAudioPlayerDelegate {
    var audioPlayer: AVAudioPlayer!

    let soundSeq = [2, 4, 5]
    var index = 0

    func playSoundSeq() {
        if index < soundSeq.count {
            loopSoundSeq(tagid: soundSeq[index])
            index += 1
        }
    }

    @IBAction func playButton(_ sender: UIButton) {
        index = 0
        playSoundSeq()
    }

    func loopSoundSeq(tagid: Int) {
        let soundURL = Bundle.main.url(forResource: "minisound\(tagid)", withExtension: "wav")!

        //machinePlay.append(sender.tag)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            audioPlayer.delegate = self
        }
        catch {
            print(soundURL)
        }

        audioPlayer.play()
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            playSoundSeq()
        }
    }
}