How to show buffer progress on AVPlayer?
I have a music player app that allows a user to stream a song from a server. I was able to stream a song from url using AVPlayer. I want to achieve something like below:
I tried to convert the top answer from this How to get file size and current file size from NSURL for AVPlayer iOS4.0 to quickly, but I can't find "kLoadedTimeRanges".
And here is my code:
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if object as? NSObject == songPlayer && keyPath == "status" {
if songPlayer?.status == AVPlayerStatus.Failed {
println("AVPlayerStatusReadyToFailed")
}else if songPlayer?.status == AVPlayerStatus.ReadyToPlay {
println("AVPlayerStatusReadyToPlay")
self.songPlayer!.play()
}else if songPlayer?.status == AVPlayerStatus.Unknown {
println("AVPlayerStatusReadyToUnknown")
}
}
}
@IBAction func playAction(sender: UIButton) {
var songUrl = "http://a575.phobos.apple.com/us/r1000/119/Music/v4/67/9d/b0/679db0ba-a7f4-35ea-3bf1-e817e7bcf11f/mzaf_3227008615944938675.aac.m4a"
var songPlayerItem = self.songPlayer?.currentItem
self.songPlayer = AVPlayer(URL: NSURL(string: songUrl))
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.songPlayer?.currentItem)
self.songPlayer?.addObserver(self, forKeyPath: "status", options: nil, context: nil)
//NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateProgress:", userInfo: nil, repeats: true)
}
I would be grateful for any suggestion, no matter using objective c or quick
source to share
Objective C:
Note: I created a custom UISlider ( Buffer Slider ) where I added one UIProgressView to show the buffer progress. setBufferValue
the method shown in the code below is a custom method that sets a value UIProgressView
.
static void *PlayerViewControllerLoadedTimeRangesObservationContext = &PlayerViewControllerLoadedTimeRangesObservationContext;
[self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:PlayerViewControllerLoadedTimeRangesObservationContext];
- (void)observeValueForKeyPath:(NSString*) path
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context
{
if (context == PlayerViewControllerLoadedTimeRangesObservationContext) {
NSArray *timeRanges = (NSArray*)[change objectForKey:NSKeyValueChangeNewKey];
if (timeRanges && [timeRanges count]) {
CMTimeRange timerange=[[timeRanges objectAtIndex:0]CMTimeRangeValue];
float bufferTimeValue=CMTimeGetSeconds(timerange.duration)/CMTimeGetSeconds(_player.currentItem.duration);
[self.playerSlider setBufferValue:bufferTimeValue>.95?1:bufferTimeValue animated:YES];
}
}
}
source to share