我有一个音乐播放器应用程序,允许用户从服务器流式传输歌曲。我已经能够使用AVPlayer从网址流式传输歌曲了。我想实现以下目标:
我试图将此How to get file size and current file size from NSURL for AVPlayer iOS4.0帖子的最高回答转换为swift,但我找不到“kLoadedTimeRanges”。
这是我的代码:
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)
}
我会感激任何建议,使用目标c或swift无关紧要
答案 0 :(得分:0)
只需使用
[avPlayerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
kLoadedTimeRanges可能只是定义为
static NSString *kLoadedTimeRanges = @"loadedTimeRanges";
答案 1 :(得分:0)
目标C:
注意:我创建了一个自定义UISlider(Buffer Slider),其中我添加了一个UIProgressView来显示缓冲区进度。下面代码中显示的setBufferValue
方法是一个自定义方法,它将设置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];
}
}
}