[swift] Swift에서 비디오 반복 재생하기

iOS 앱을 개발하다 보면, 비디오를 반복해서 재생해야 하는 경우가 있습니다. Swift에서는 AVFoundation 프레임워크를 사용하여 비디오를 재생하고 반복하는 기능을 구현할 수 있습니다. 이번 글에서는 Swift로 비디오를 반복 재생하는 방법에 대해 알아보겠습니다.

비디오 파일 추가

먼저, 프로젝트에 비디오 파일을 추가해야 합니다. 비디오 파일을 프로젝트에 추가한 후에는 해당 파일을 참조하여 비디오를 재생하고 반복할 수 있습니다.

AVPlayer 및 AVPlayerLayer 사용

AVPlayer는 비디오를 재생하는 데 사용되는 객체이며, AVPlayerLayer는 비디오를 화면에 표시하는 데 사용됩니다. AVPlayer와 AVPlayerLayer를 사용하여 비디오를 반복해서 재생할 수 있습니다.

import AVFoundation
import AVKit
import UIKit

class ViewController: UIViewController {
    var player: AVPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        playVideo()
    }

    func playVideo() {
        if let path = Bundle.main.path(forResource: "video", ofType: "mp4") {
            let videoURL = URL(fileURLWithPath: path)
            player = AVPlayer(url: videoURL)

            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = view.bounds
            playerLayer.videoGravity = .resizeAspectFill
            view.layer.addSublayer(playerLayer)

            player.seek(to: CMTime.zero)
            player.play()

            NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { notification in
                self.player.seek(to: CMTime.zero)
                self.player.play()
            }
        }
    }
}

위의 코드는 AVPlayer와 AVPlayerLayer를 사용하여 비디오를 반복해서 재생하는 기능을 구현한 예시입니다. 비디오 재생이 끝나면 AVPlayerItemDidPlayToEndTime 노티피케이션을 받아서 다시 처음으로 돌아가고 재생합니다.

결론

Swift에서 AVFoundation 프레임워크를 이용하여 비디오를 반복 재생하는 방법에 대해 알아보았습니다. 이를 통해 iOS 앱에서 비디오를 반복해서 재생하는 기능을 구현할 수 있습니다.

참고 자료: Apple Developer Documentation - AVFoundation