[swift] 스위프트에서 미디어 플레이어 상태 모니터링

iOS 앱을 개발할 때, 미디어 플레이어를 사용하여 오디오나 비디오를 재생하는 기능을 구현해야 하는 경우가 있습니다. 이때, 플레이어의 상태를 모니터링하고 적절히 처리해야 합니다.

AVPlayer 상태 모니터링

AVPlayer를 사용하여 미디어를 재생할 때, 플레이어의 상태를 모니터링하기 위해 Key-Value Observing (KVO)를 사용할 수 있습니다. 예를 들어, 재생 상태가 변경될 때마다 알림을 받고자 한다면 다음과 같이 코드를 작성할 수 있습니다.

let player = AVPlayer(url: url)

player.addObserver(self, forKeyPath: "timeControlStatus", options: .new, context: nil)

// ...

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "timeControlStatus", let newStatusInt = change?[.newKey] as? Int, let newStatus = AVPlayer.TimeControlStatus(rawValue: newStatusInt) {
        // Handle the new time control status
    }
}

AVPlayerItem 상태 모니터링

또한, AVPlayerItem을 사용하여 미디어를 재생하는 경우에는 AVPlayerItem 객체의 여러 속성을 통해 상태를 모니터링할 수 있습니다. 예를 들어, status 속성을 사용하여 재생 아이템의 상태를 확인할 수 있습니다.

let playerItem = AVPlayerItem(url: url)

// ...

playerItem.addObserver(self, forKeyPath: "status", options: .new, context: nil)

// ...

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "status", let newStatusInt = change?[.newKey] as? Int, let newStatus = AVPlayerItem.Status(rawValue: newStatusInt) {
        // Handle the new status
    }
}

위의 예시 코드를 참고하여, 미디어 플레이어의 상태를 모니터링하고 필요한 처리를 구현할 수 있습니다.