Swift 2: AVAudioPlayers to play multiple sounds at once

自古美人都是妖i 提交于 2019-12-04 10:19:44

This question sounds more like you don't quite have a grasp on Swift data structures, but here's a simple snippet to get you on your way:

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)
        }


    }

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