THIS IS ELLIE

AVPlayer에서 플레이어 상태 파악하기 본문

개발/iOS

AVPlayer에서 플레이어 상태 파악하기

Ellie Kim 2020. 10. 12. 18:34

아래 설명과 같이 AVPlayer는 상태가 계속해서 변경되는 동적 객체입니다.

플레이어의 상태을 관찰할 수 방법이 두 가지 방법이 존재합니다.

(AVPlayer 애플 공식문서 링크에서 확인 가능합니다. developer.apple.com/documentation/avfoundation/avplayer)

그중에서도 일반 상태 관찰을 위해 옵저버를 통해서 상태 변화를 받아보도록 했습니다.

상태 변화를 받기 위해서는 observeValue(forKeyPath:of:change:context:) 메서드를 구현해야 합니다.

override func observeValue(forKeyPath keyPath: String?,
                           of object: Any?,
                           change: [NSKeyValueChangeKey : Any]?,
                           context: UnsafeMutableRawPointer?) {

    // Only handle observations for the playerItemContext
    guard context == &playerItemContext else {
        super.observeValue(forKeyPath: keyPath,
                           of: object,
                           change: change,
                           context: context)
        return
    }

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

        // Switch over status value
        switch status {
        case .readyToPlay:
            // Player item is ready to play.
        case .failed:
            // Player item failed. See error.
        case .unknown:
            // Player item is not yet ready.
        }
    }
}

상태를 보면 3가지 상태가 있는 것을 확인할 수 있습니다.

AVPlayer의 상태를 확인할 수 있는 status변수가 있습니다.

이는 Enum으로 AVPlayer.Status에 3가지 케이스가 존재합니다.

3가지 케이스는 unknown, readyToPlay, failed가 있습니다.

unknown은 재생을 위해 새 미디어 리소스를 로드하지 않은 상태로 알 수 없는 상태입니다. 

readyToPlay는 플레이어가 아이템들을 재생할 준비가 된 상태입니다.

failed는 에러로 더 이상 재생할 수 없는 상태입니다.

 

추가로 플레이 중 버퍼링의 상태가 어떤지도 궁금한데 그럴 때는

redayToPlay상태 내에 아래와 같이 코드를 추가로 작성해 파악할 수도 있습니다.

if (AVPlayerItem.isPlaybackLikelyToKeepUp) {
    NSLog(@" Playing");
} else if (AVPlayerItem.isPlaybackBufferEmpty) {
    NSLog(@" Buffer empty - show loader");
} else if (AVPlayerItem.isPlaybackBufferFull) {
    NSLog(@" Buffer full - hide loader");
} else {
    NSLog(@" Buffering ");
}

 

resource:

developer.apple.com/documentation/avfoundation/avplayer/1388096-status

developer.apple.com/documentation/avfoundation/media_playback_and_selection/responding_to_playback_state_changes

반응형