杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//
//  HomeTopMenuView.swift
//  XQMuse
//
//  Created by 无故事王国 on 2024/8/12.
//
 
import UIKit
import JQTools
import RxSwift
import AVFoundation
 
enum ImageFromType {
                case local
                case url
}
 
struct HomeTopMenuItem{
                var id = 0
                var title = ""
                var image = ""
                var imageFrom:ImageFromType = .local
}
 
class HomeTopMenuView: UIView,JQNibView{
 
                @IBOutlet weak var image_top: UIImageView!
                @IBOutlet weak var menu_collectionView: UICollectionView!
                @IBOutlet weak var menu_height: NSLayoutConstraint!
                
                private var disposeBag = DisposeBag()
                private var defaultItems = [HomeTopMenuItem]()
                private var clouse:((HomeTopMenuItem)->Void)?
    private let session = URLSession.shared
    private var aVPlayerLayer:AVPlayerLayer?
 
                override func awakeFromNib() {
                                super.awakeFromNib()
 
        image_top.layer.masksToBounds = true
        image_top.image = UIImage(named: "home_top_bg")
                                menu_height.constant = 119
                                menu_collectionView.delegate = self
                                menu_collectionView.dataSource = self
                                menu_collectionView.isScrollEnabled = false
                                menu_collectionView.register(UINib(nibName: "HomeTopMenuCCell", bundle: nil), forCellWithReuseIdentifier: "_HomeTopMenuCCell")
 
                                defaultItems.append(HomeTopMenuItem(title: "睡眠疗愈", image: "icon_sleep", imageFrom: .local))
                                defaultItems.append(HomeTopMenuItem(title: "高频疗愈", image: "icon_band", imageFrom: .local))
                                defaultItems.append(HomeTopMenuItem(title: "清业疗愈", image: "icon_quiet", imageFrom: .local))
                                defaultItems.append(HomeTopMenuItem(title: "亲子疗愈", image: "icon_parent-child", imageFrom: .local))
                                menu_collectionView.reloadData()
 
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { [weak self] data in
            self?.aVPlayerLayer?.player?.seek(to: .zero)
            self?.aVPlayerLayer?.player?.play()
        }
 
        if let url = Bundle.main.url(forResource: "bg_water", withExtension: "mov"){
            setPlayer(url: url)
        }
 
                }
 
                func resetTopImage(){
        var needLocalVideo = false
        if let imgUrl = UserDefaultSettingViewModel.getSetting()?.sceneMusicModel?.imageUrl.jq_urlEncoded(),imgUrl.isEmpty == false{
                                                image_top.sd_setImage(with: URL(string: imgUrl))
        }else{
            image_top.image = UIImage(named: "home_top_bg")
            needLocalVideo = true
        }
 
        if let model = UserDefaultSettingViewModel.getSetting()?.sceneMusicModel{
 
            aVPlayerLayer?.player?.pause()
            aVPlayerLayer?.removeFromSuperlayer()
            aVPlayerLayer = nil
 
            if model.backName?.isEmpty ?? true && model.imageUrl.isEmpty == false{
                image_top.sd_setImage(with: URL(string: model.imageUrl.jq_urlEncoded()))
            }
 
            if let videoUrl = model.backUrl,videoUrl.isEmpty == false{
                checkCacheAudio(from: URL(string: videoUrl)!) {[unowned self] state, url in
                    self.setPlayer(url: url)
                }
                return
            }
 
            if needLocalVideo{
                if let url = Bundle.main.url(forResource: "bg_water", withExtension: "mov"){
                    setPlayer(url: url)
                }
            }
        }
                }
 
    private func setPlayer(url:URL){
 
        let player = AVPlayer(url: url)
        player.play()
        player.isMuted = true
 
        if aVPlayerLayer == nil{
            aVPlayerLayer = AVPlayerLayer()
            aVPlayerLayer = AVPlayerLayer(player: player)
            aVPlayerLayer?.frame = image_top.frame
            aVPlayerLayer?.videoGravity = .resizeAspectFill
            self.layer.addSublayer(aVPlayerLayer!)
        }
    }
 
    // 下载视频并缓存,如果没有缓存,原路返回并异步下载
    internal func checkCacheAudio(from url: URL, completion: @escaping (Bool,URL) -> Void) {
 
        let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("bgVideos")
 
        let videoCacheUrl = cacheDirectory.appendingPathComponent(url.lastPathComponent.jq_md5String() + "." + url.pathExtension)
 
        // 检查缓存中是否已存在文件
        if FileManager.default.fileExists(atPath: videoCacheUrl.path) {
            print("启用缓存")
            completion(true,videoCacheUrl)
            return
        }else{
            completion(false,url)
            print("没有缓存:执行下载")
        }
 
        // 使用URLSession下载视频
        let downloadTask = session.downloadTask(with: url) {
            tempLocalUrl, response, error in
            print("执行下载任务")
            if let tempLocalUrl = tempLocalUrl, error == nil {
                do {
                    let temp = videoCacheUrl
 
                    if !(FileManager.default.fileExists(atPath: cacheDirectory.path)){
                        try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
                    }
 
                    try FileManager.default.moveItem(at: tempLocalUrl, to: temp)
                } catch let e {
                    print("视频缓存失败:catch:\(e)")
 
 
 
                }
            } else {
                print("视频缓存失败:\(error?.localizedDescription ?? "")")
            }
        }
        downloadTask.resume()
    }
 
                func resetItems(_ items:[HomeTopMenuItem]){
                                defaultItems.removeAll()
                                defaultItems = items
                                menu_collectionView.reloadData()
                }
 
                func insertOthers(_ others:[HomeTopMenuItem]){
                                defaultItems.append(contentsOf: others)
                                menu_collectionView.reloadData()
                }
 
 
                func clickItemAt(_ clouse: @escaping (HomeTopMenuItem)->Void){
                                self.clouse = clouse
                }
}
 
 
extension HomeTopMenuView:UICollectionViewDelegate & UICollectionViewDataSource{
 
                func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                                let item = defaultItems[indexPath.row]
                                clouse?(item)
                }
 
 
                func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                                return defaultItems.count
                }
                
                func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_HomeTopMenuCCell", for: indexPath) as! HomeTopMenuCCell
                                cell.setItem(defaultItems[indexPath.row])
                                cell.view_line.isHidden = indexPath.row == 3
                                return cell
                }
}
 
extension HomeTopMenuView:UICollectionViewDelegateFlowLayout{
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
                                return 0
                }
 
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
                                return 0
                }
 
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                                let w = JQ_ScreenW / 4.0
                                return CGSize(width: w, height: 119)
                }
}