import AVFoundation
class YourClass: ..., AVAudioPlayerDelegate {
var player: AVAudioPlayer?
var yourURLStrings:[String] = []
override func viewDidLoad() {
self.playSound(position: 0)
}
func playSound(position: Int) {
let firstURL = yourURLStrings[position]
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
//Set delegate to self so we can execute delegate `AVAudioPlayerDelegate` functions
player.delegate = self
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
self.yourURLStrings.remove(at: 0)
if(yourURLStrings.count > 0) {
self.playSound(position: 0)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…