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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
func playMovie(movieFile: String, captionFile: String) -> Bool {
let fileManage = FileManager.default
guard fileManage.fileExists(atPath: movieFile) && fileManage.fileExists(atPath: captionFile) else {
debugPrint("movie:\(movieFile)/ or captionFile:\(captionFile)not found")
return false
}
player = AVPlayer(url: URL(fileURLWithPath: movieFile))
let asset = AVAsset(url: URL(fileURLWithPath: captionFile))
for characteristic in asset.availableMediaCharacteristicsWithMediaSelectionOptions {
print("\(characteristic)")
// Retrieve the AVMediaSelectionGroup for the specified characteristic.
if let group = asset.mediaSelectionGroup(forMediaCharacteristic: characteristic) {
// Print its options.
for option in group.options {
print(" Option: \(option.displayName)")
}
}
}
if let group = asset.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristic.legible) {
let locale = Locale(identifier: "en")
let options =
AVMediaSelectionGroup.mediaSelectionOptions(from: group.options, with: locale)
if let option = options.first {
// Select Spanish-language subtitle option
player?.currentItem!.select(option, in: group)
print("\(player?.currentItem!.select(option, in: group))")
}
}
playerLayer = AVPlayerLayer(player: player)
playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerContainerView?.layer.addSublayer(playerLayer!)
player?.currentItem?.addObserver(self, forKeyPath:ViewController.observerKeyStatus, options:[NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.initial], context: nil)
player?.currentItem?.addObserver(self, forKeyPath: ViewController.observerKeyLoadedTimeRanges, options: NSKeyValueObservingOptions.new, context: nil)
// Subtitle file
let subtitleFile = Bundle.main.path(forResource: "test", ofType: "srt")
let subtitleURL = URL(fileURLWithPath: subtitleFile!)
// Subtitle parser
parser = Subtitles(file: subtitleURL, encoding: .utf8)
player?.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] (time: CMTime) in
let currentTime = CMTimeGetSeconds(time)
guard let self = self else {
return
}
self.movieTextLabel?.text = self.parser?.searchSubtitles(at: currentTime)
let totolCTTime = self.player?.currentItem?.duration ?? CMTimeMake(value: 0, timescale: 0)
let totalTime = CMTimeGetSeconds(totolCTTime)
if totalTime > 0 {
self.slider?.value = Float(currentTime/totalTime)
}
})
return true
}
|