0

I have 10 URL of music files. I want to create music queue where all songs play one by one, and also I can change the index of particular file.

I am using swift 2.0

For ex: iPhone's Default Playlist Playing.

  • Possible duplicate of [AVAudioPlayer - playing multiple audio files, in sequence](http://stackoverflow.com/questions/621182/avaudioplayer-playing-multiple-audio-files-in-sequence) – Badal Shah Oct 16 '15 at 05:09
  • Thanks @Badal but i need swift 2.0 Version. –  Oct 16 '15 at 05:11

1 Answers1

2

You can use AVAudioPlayerDelegate for that as shown into below example code:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    var counter = 0
    var song = ["1","2","3"] //Song names array
    var player = AVAudioPlayer()

    @IBOutlet weak var musicSlider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()
        musicSlider.value = 0.0
    }

    func updateMusicSlider(){

        musicSlider.value = Float(player.currentTime)
    }

    @IBAction func playSong(sender: AnyObject) {

        music()
    }
    @IBAction func sliderAction(sender: AnyObject) {

        player.stop()
        player.currentTime = NSTimeInterval(musicSlider.value)
        player.play()
    }

    func music(){

        let audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "mp3")!
        var error : NSError? = nil
        do {
            player = try AVAudioPlayer(contentsOfURL: NSURL(string: audioPath)!)
        } catch let error1 as NSError {
            error = error1
        }
        musicSlider.maximumValue = Float(player.duration)
        NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
        player.delegate = self
        if error == nil {
            player.delegate = self
            player.prepareToPlay()
            player.play()
        }
    }
    // Delegate method for AVAudioPlayerDelegate which is called every time when song finished. 
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool){

        if flag {
            counter++
        }

        if ((counter + 1) == song.count) {
            counter = 0
        }

        music()
    }
}

Sample for more Info.

Hope it will help.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165