[swift] 스위프트에서 로컬 비디오 재생하기
로컬 비디오를 iOS 앱에서 재생해보고 싶으신가요? 이번 포스트에서는 Swift를 사용하여 iOS 앱에서 로컬 비디오를 재생하는 방법에 대해 알아봅시다.
비디오 파일 추가
먼저, 비디오 파일을 Xcode 프로젝트에 추가합니다. 프로젝트 내에 비디오 파일이 없는 경우에는, 원하는 비디오 파일을 Xcode 프로젝트로 드래그 앤 드롭하여 추가합니다.
AVPlayer 사용
로컬 비디오를 재생하기 위해 AVPlayer
를 사용할 것입니다. 다음 코드는 AVPlayer
를 생성하고 비디오 파일을 로드하는 방법을 보여줍니다.
import AVKit
import AVFoundation
class VideoPlayerViewController: UIViewController {
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
if let videoPath = Bundle.main.path(forResource: "sample", ofType: "mp4") {
let videoURL = URL(fileURLWithPath: videoPath)
player = AVPlayer(url: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = view.bounds
view.layer.addSublayer(playerLayer)
player?.play()
}
}
}
위 코드에서 AVPlayer
는 비디오 파일의 URL을 사용하여 초기화되고, AVPlayerLayer
를 사용하여 비디오를 화면에 표시합니다. AVPlayer
의 play
메서드를 호출하여 비디오를 재생합니다.
플레이어 컨트롤러 추가
AVPlayerViewController
를 사용하여 비디오 재생 화면에 플레이어 컨트롤러를 추가할 수도 있습니다. 아래 코드는 AVPlayerViewController
를 사용하여 비디오를 재생하는 방법을 보여줍니다.
import AVKit
import AVFoundation
class VideoPlayerViewController: UIViewController {
var playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
if let videoPath = Bundle.main.path(forResource: "sample", ofType: "mp4") {
let videoURL = URL(fileURLWithPath: videoPath)
let player = AVPlayer(url: videoURL)
playerViewController.player = player
present(playerViewController, animated: true) {
player.play()
}
}
}
}
요약
이제 Swift를 사용하여 iOS 앱에서 로컬 비디오를 재생하는 방법에 대해 살펴보았습니다. AVPlayer
및 AVPlayerViewController
를 사용하여 비디오를 재생하고 화면에 표시할 수 있습니다. 원하는 방식을 선택하여 로컬 비디오를 즐겨보세요!
참고: Apple Developer Documentation - AVKit