play sequential audio files swift

1.1k views Asked by At

hi im trying to play several audio files one after the other.

here's the code I have to play 1 audio file names "1". can anyone help us play a group of audio files sequentiall?

import UIKit
import AVFoundation

class ViewController: UIViewController {

var ding:AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()



    prepareAudios()
    ding.play()


}

func prepareAudios() {

    var path = NSBundle.mainBundle().pathForResource("1", ofType: "mp3")
    ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil)
    ding.prepareToPlay()

   }


}
1

There are 1 answers

4
Sandeep On

You can use AVQueuePlayer to play multiple audio sequentially.

 class ViewController: UIViewController {
    var playerQueue: AVQueuePlayer = {
    let url1 = NSBundle.mainBundle().URLForResource("UpTown", withExtension: "mp3")!
    let url2 = NSBundle.mainBundle().URLForResource("TurnMeOn", withExtension: "mp3")!

    let item1 = AVPlayerItem(URL: url1)
    let item2 = AVPlayerItem(URL: url2)

    let queue = AVQueuePlayer(items: [item1, item2])
    return queue
    }()

  override func viewDidLoad() {
    super.viewDidLoad()
    playerQueue.play()
  }
}