Ben*_*man 15 objective-c ios avplayer
我有一个使用AVPlayer构建的音频播放器.
目前,我把player
情况和周围时,我需要换轨(无论是从手动选择或轨道已经到达末端),我创建了一个新的AVPlayerItem
,我称之为replaceCurrentItemWithPlayerItem
新项目.
根据文档,replaceCurrentItemWithPlayerItem
是一个异步操作,所以我也观察了播放器的currentItem键路径.当它被调用时,我告诉我的玩家玩.
这是相关代码:
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerItemStatusChangedContext];
if (!_player) {
_player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerStatusChangedContext];
[_player addObserver:self forKeyPath:@"currentItem" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerCurrentItemChangedContext];
} else {
[_player replaceCurrentItemWithPlayerItem:playerItem];
}
Run Code Online (Sandbox Code Playgroud)
这里是关键值观察回调:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == CHStreamingAudioPlayer_PlayerCurrentItemChangedContext) {
NSLog(@"Player's current item changed! Change dictionary: %@", change);
if (_player.currentItem) {
[self play]; //<---- doesn't get called
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
Run Code Online (Sandbox Code Playgroud)
在iOS 4.3.3(和iOS 5)上,我的关键观察方法被调用,但_player.currentItem
总是如此nil
.在4.2.1和4.3.2上,此属性包含实际值.永远不会再调用此方法.所以从本质上讲,替换似乎总是失败.
这似乎是一个错误,但也许我做错了什么.
XCo*_*ool 17
我在iOS 5(包括5.0.1)中遇到了这个问题.它曾经在iOS 4.x上正常工作.
有两种方法可以解决此问题,每次需要交换曲目时,都可以AVPlayer
使用所需的AVPlayerItem
s来释放和重新创建.或者,只需调用replaceCurrentItemWithPlayerItem:
主线程即可.
我尝试了两种选择,但它们运行良好.
致记自:Apple开发者论坛
归档时间: |
|
查看次数: |
16120 次 |
最近记录: |