Skip to content

Instantly share code, notes, and snippets.

@ronanrodrigo
Created January 13, 2017 11:58
Show Gist options
  • Select an option

  • Save ronanrodrigo/d067d11adb0057f555bcf2966e5eb6a0 to your computer and use it in GitHub Desktop.

Select an option

Save ronanrodrigo/d067d11adb0057f555bcf2966e5eb6a0 to your computer and use it in GitHub Desktop.
import UIKit
import AVFoundation
import PlaygroundSupport
class Player: NSObject {
var player: AVQueuePlayer!
var playerItem: AVPlayerItem!
var playerContext = 0
override init() {
super.init()
let itemURL = URL(string: "https://ia802704.us.archive.org/6/items/AlannSteenHostageReleaseDocumentary1991/AlannSteen.mp3")!
playerItem = AVPlayerItem(url: itemURL)
playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.initial, .new], context: &playerContext)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let playerItem = object as? AVPlayerItem, let first = playerItem.loadedTimeRanges.first {
let loaded = first.timeRangeValue.duration.value.hashValue / first.timeRangeValue.duration.timescale.hashValue
let total = playerItem.duration.value.hashValue / playerItem.duration.timescale.hashValue
print("\((loaded*100)/total)%")
}
}
func play() {
player = AVQueuePlayer(playerItem: playerItem)
player.play()
}
deinit {
playerItem.removeObserver(self, forKeyPath: "loadedTimeRanges")
}
}
var player = Player()
player.play()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment