import UIKit
import AVFoundation
private var players:[AVAudioPlayer] = []
class AVAudioPlayerPool: NSObject {
func playerWithURL(url:URL) -> AVAudioPlayer? {
let availabelPlayers = players.filter { (player) -> Bool in
return player.isPlaying == false && player.url == url
}
if let playerToUse = availabelPlayers.first{
return playerToUse
}
do {
let newPlayer = try AVAudioPlayer(contentsOf: url)
players.append(newPlayer)
return newPlayer
} catch {
print(error)
}
return nil
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let url = Bundle.main.url(forResource: "test1", withExtension: "wav") {
let player = AVAudioPlayerPool().playerWithURL(url: url)
player?.play()
}
}
}
Demo-18 使用多个AVAudioPlayer