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

时间:2016-05-04 16:15:10

标签: swift swift2 avaudioplayer

嘿嘿

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

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

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同步的代码片段,这样我就可以播放声音而不会删除正在播放的任何其他声音。即使两次声音效果相同。

1 个答案:

答案 0 :(得分:8)

这个问题听起来更像是你对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)
        }


    }

}