Swift 2: AVAudioPlayers 一次播放多种声音

Swift 2: AVAudioPlayers to play multiple sounds at once

所以嘿

我一直在四处寻找,试图找到解决这个问题的方法,但基本上还没有解决这个问题。

我迫切需要一种方法来随时实例化和播放声音,而不会切断任何其他声音。我知道 AVAudioPlayer 一次只能播放一种声音,所以我想弄清楚如何制作一个动态的 AVAudioPlayer 数组,我可以在需要播放声音的任何时候添加它。我从本网站上的不同答案得到的当前代码是:

func Sound(sound: String) {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource(sound, ofType: "wav") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
    } catch {
        print(error)
    }


}

不幸的是,这不起作用。它播放一个声音,但停止播放任何其他声音。

I've also tried the code from here, but I'm having the same problem the asker is having, and there's no solution.

基本上,我只需要一个与 Swift 2 同步的代码片段,它可以让我播放一个声音而不会切断正在播放的任何其他声音。哪怕是两次一样的音效

这个问题听起来更像是你不太了解 Swift 数据结构,但这里有一个简单的片段可以帮助你上路:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var arrayOfPlayers = [AVAudioPlayer]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        sound("tester")
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
            self.sound("tester")
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func sound(sound: String) {
        do {
            if let bundle = NSBundle.mainBundle().pathForResource(sound, ofType: "wav") {
                let alertSound = NSURL(fileURLWithPath: bundle)
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
                try AVAudioSession.sharedInstance().setActive(true)
                let audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
                arrayOfPlayers.append(audioPlayer)
                arrayOfPlayers.last?.prepareToPlay()
                arrayOfPlayers.last?.play()
            }
        } catch {
            print(error)
        }


    }

}