Skip to content

Instantly share code, notes, and snippets.

@amratab
Created May 27, 2016 10:15
Show Gist options
  • Save amratab/0b93ec0e60fce89ca3061800c2f76a47 to your computer and use it in GitHub Desktop.
Save amratab/0b93ec0e60fce89ca3061800c2f76a47 to your computer and use it in GitHub Desktop.
var player: AVQueuePlayer!
//for sound of assets let sound = NSDataAsset(name: "audio")
func viewDidLoad() {
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
let item = AVPlayerItem(URL: NSURL(string: "http://incompetech.com/music/royalty-free/mp3-royaltyfree/Motherlode.mp3")!)
let item2 = AVPlayerItem(URL: NSURL(string: "http://incompetech.com/music/royalty-free/mp3-royaltyfree/Vicious.mp3")!)
player = AVQueuePlayer(items: [ item, item2])
player.actionAtItemEnd = .Advance
player.addObserver(self, forKeyPath: "currentItem", options: [.New, .Initial], context: nil)
// player.addObserver(self, forKeyPath: "currentItem", options: .New ? .New : .Initial , context: nil)
player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 100), queue: dispatch_get_main_queue()) {
[unowned self] time in
let timeString = String(format: "%02.2f", CMTimeGetSeconds(time))
if UIApplication.sharedApplication().applicationState == .Active {
self.titleLabel.text = timeString
} else {
print("Background: \(timeString)")
}
}
}
@IBAction func playPauseAction(sender: UIButton) {
sender.selected = !sender.selected
if sender.selected {
player.play()
} else {
player.pause()
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "currentItem" {
let player = object as? AVPlayer
let currentItem = player!.currentItem?.asset as? AVURLAsset
songLabel.text = currentItem!.URL.lastPathComponent ?? "Unknown"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment