如何知道AVPlayerItem何时播放

时间:2014-04-16 19:22:33

标签: ios avqueueplayer

我遇到AVPlayerItemAVQueuePlayer的问题。目前我有很多1-2秒长的音乐文件和一个按顺序播放它们的队列播放器。

我想要的是知道音乐文件刚刚开始播放,而不是当它完成播放时(通过AVPlayerItemDidPlayToEndTimeNotification)。

这是因为我想在加载和播放新文件时运行一个函数。

我的代码:

 for (NSUInteger i = 0; i < [matchedAddr count]; i++)
{
    NSString *firstVideoPath = [[NSBundle mainBundle] pathForResource:[matchedAddr objectAtIndex:i] ofType:@"wav"];
    //NSLog(@"file %@",firstVideoPath);
    avitem=[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstVideoPath]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(currentItemIs:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:avitem];

    [filelist addObject:avitem];
}
 player = [AVQueuePlayer queuePlayerWithItems:filelist];
[player play];


- (void)currentItemIs:(NSNotification *)notification
{
    NSString *asd=[seqArray objectAtIndex:currentColor];
    currentColor=currentColor+1;
    AVPlayerItem *p = [notification object];
    [p seekToTime:kCMTimeZero];

    if([asd isEqual:@"1"])
    {
        [UIView animateWithDuration:0.01 animations:^{
           one.alpha = 0;
        } completion:^(BOOL finished) {

            [UIView animateWithDuration:0.01 animations:^{
               one.alpha = 1;
            }];
        }];
    }
}

正如您所看到的,currentItemIs void被调用,但它在轨道播放完毕后运行。我希望在轨道开始时调用。

修改 Winston的代码片段的更新版本:

NSString * const kStatusKey         = @"status";

        [avitem addObserver:self
                              forKeyPath:kStatusKey
                                 options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                                 context:@"AVPlayerStatus"];
- (void)observeValueForKeyPath:(NSString *)path
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if (context == @"AVPlayerStatus") {

        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status) {
            case AVPlayerStatusUnknown: {

            }
                break;

            case AVPlayerStatusReadyToPlay: {
                // audio will begin to play now.
                NSLog(@"PLAU");
                [self playa];
            }
                break;
        }
    }
}

2 个答案:

答案 0 :(得分:5)

首先,您需要将AVPlayerItem注册为观察员

[self.yourPlayerItem addObserver:self
                      forKeyPath:kStatus
                         options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                         context:AVPlayerStatus];

然后,在您的播放器键值观察器方法中,您需要检查AVPlayerStatusReadyToPlay 状态,如下所示:

- (void)observeValueForKeyPath:(NSString *)path
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

     if (context == AVPlayerStatus) {

        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status) {
            case AVPlayerStatusUnknown: {

            }
            break;

            case AVPlayerStatusReadyToPlay: {
                // audio will begin to play now.
            }
            break;
   }
}

答案 1 :(得分:3)

以下应该有效:

观察玩家的状态:

let playerItem: AVPlayerItem = AVPlayerItem(asset: videoPlusSubtitles, automaticallyLoadedAssetKeys: requiredAssetKeys)

playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [], context: nil)

player = AVPlayer(playerItem: playerItem)

响应状态更改:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItem.Status

        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }

        // Switch over status value
        switch status {
        case .readyToPlay:
            print("Player item is ready to play.")
            break
        case .failed:
            print("Player item failed. See error")
            break
        case .unknown:
            print("Player item is not yet ready")
            break
        @unknown default:
            fatalError()
        }
    }
}