[iOS/Snippet] 자막과 함께 동영상 재생하기

urlvtt형식의 자막파일을 같이 받았을 때, 동영상을 전체화면으로 재생하는 소스코드다.

만약 앱 내부에 동영상 플레이어를 위치시키고 싶다면 하단의 소스 몇줄만 수정해주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import AVKit

func playVideo(url: String, vtt: String) {
guard let myURL = URL(string: url) else { return }
guard let mySubtitleURL = URL(string: vtt) else { return }
let videoAsset = AVAsset(url: myURL)
let subtitleAsset = AVAsset(url: mySubtitleURL)
let mixComposition = AVMutableComposition()

let videoTrack = mixComposition.addMutableTrack(
withMediaType: .video,
preferredTrackID: kCMPersistentTrackID_Invalid
)
let audioTrack = mixComposition.addMutableTrack(
withMediaType: .audio,
preferredTrackID: kCMPersistentTrackID_Invalid
)
let subtitleTrack = mixComposition.addMutableTrack(
withMediaType: .text,
preferredTrackID: kCMPersistentTrackID_Invalid
)
let videoDuration = CMTimeRange(start: kCMTimeZero, end: videoAsset.duration)

try! videoTrack?.insertTimeRange(
videoDuration,
of: videoAsset.tracks(withMediaType: .video)[0],
at: kCMTimeZero
)
try! audioTrack?.insertTimeRange(
videoDuration,
of: videoAsset.tracks(withMediaType: .audio)[0],
at: kCMTimeZero
)
try! subtitleTrack?.insertTimeRange(
videoDuration,
of: subtitleAsset.tracks(withMediaType: .text)[0],
at: kCMTimeZero
)

let player = AVPlayer(playerItem: AVPlayerItem(asset: mixComposition))
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
Share