How to play the same sound overlapping with AVAudioPlayer?

我与影子孤独终老i 提交于 2019-12-01 10:41:55

To play two sounds simultaneously with AVAudioPlayer you just have to use a different player for each sound.

In my example I've declared two players, playerBoom and playerCrash, in the Viewcontroller, and I'm populating them with a sound to play via a function, then trigger the play at once:

import AVFoundation

class ViewController: UIViewController {

    var playerBoom:AVAudioPlayer?
    var playerCrash:AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        playerBoom = preparePlayerForSound(named: "sound1")
        playerCrash = preparePlayerForSound(named: "sound2")

        playerBoom?.prepareToPlay()
        playerCrash?.prepareToPlay()
        playerBoom?.play()
        playerCrash?.play()

    }

    func preparePlayerForSound(named sound: String) -> AVAudioPlayer? {
        do {
            if let soundPath = NSBundle.mainBundle().pathForResource(sound, ofType: "mp3") {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)
                return try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: soundPath))
            } else {
                print("The file '\(sound).mp3' is not available")
            }
        } catch let error as NSError {
            print(error)
        }
        return nil
    }

}

It works very well but IMO is not suitable if you have many sounds to play. It's a perfectly valid solution for just a few ones, though.

This example is with two different sounds but of course the idea is exactly the same for two identic sounds.

I could not find a solution using just AVAudioPlayer.

Instead, I have found a solution to this problem with a library that is built on top of AVAudioPlayer.

The library allows same sounds to be played overlapped with each other.

https://github.com/adamcichy/SwiftySound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!