杨锴
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
//
//  BackgroundVoiceVC.swift
//  XQMuse
//
//  Created by 无故事王国 on 2024/8/14.
//
 
import UIKit
import QMUIKit
import JQTools
 
class BackgroundVoiceVC: BaseVC {
 
//                @IBOutlet weak var slider_voice: UISlider!
                @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var sceneSwitch: UISwitch!
    
                private var items = [BGMModel]()
                private var settingModel = UserDefaultSettingViewModel.getSetting()
                private var audioPlayer = AudioPlayer.getSharedInstance()
                private var playAtIndex:IndexPath?
                private var tempPlayer:AVPlayer?
                private var isPlaying:Bool = false
    private var needPopRoot = false
    private var isFromFist = false
 
                override func viewDidDisappear(_ animated: Bool) {
                                super.viewDidDisappear(animated)
        if audioPlayer.meditationModel != nil{
//            audioPlayer.masterPlayer?.play()
//            audioPlayer.bgmPlayer?.play()
        }else{
            if sceneSwitch.isOn{
                audioPlayer.playScene()
            }
        }
                }
 
                override func viewDidAppear(_ animated: Bool) {
                                super.viewDidAppear(animated)
                                audioPlayer.pauseScene()
        if audioPlayer.meditationModel != nil{
//            audioPlayer.masterPlayer?.pause()
            audioPlayer.bgmPlayer?.pause()
            PayMusicVC.updateStatus(.pause)
        }
                }
 
    init(isFromFist:Bool){
        super.init(nibName: nil, bundle: nil)
        self.isFromFist = isFromFist
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
                override func viewDidLoad() {
        super.viewDidLoad()
                                title = "泉疗愈"
 
        sceneSwitch.isOn = UserViewModel.getSceneSwitch()
 
        yy_popBlock = { [weak self] in
            if self?.needPopRoot ?? false{
                if JQ_currentNavigationController().viewControllers.first is PlanGuideVC{
                    NotificationCenter.default.post(name: PlantGuideQuit_Noti, object: nil, userInfo: nil)
                }else{
                    self?.navigationController?.popViewController(animated: true)
                }
            }else{
                self?.navigationController?.popViewController(animated: true)
            }
        }
 
//                                slider_voice.isEnabled = false
//                                slider_voice.value = Float(settingModel?.volume ?? 0.5)
                                Services.getBGM().subscribe(onNext: {[unowned self]data in
                                                if let m = data.data{
                                                                self.items = m
//                                                                self.slider_voice.isEnabled = true
                                                                self.collectionView.reloadData()
 
                                                                DispatchQueue.main.asyncAfter(delay: 0.8) {
                                                                                for (index,v) in m.enumerated(){
                                                                                                if v.id == self.settingModel?.sceneMusicModel?.id{
                                                                                                                self.playAtIndex = IndexPath(row: index, section: 0)
                                                                                                                self.collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: true)
                                                                                                                break
                                                                                                }
                                                                                }
                                                                                self.collectionView.reloadData()
                                                                }
                                                }
                                }).disposed(by: disposeBag)
 
                                //播放完成
                                NotificationCenter.default.addObserver(self, selector: #selector(playBGMbackEnd), name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    }
 
                override func setUI() {
 
                                let v1 = UIView()
                                v1.backgroundColor = UIColor(hexStr: "#B6DC90")
                                v1.bounds = CGRect(x: 0, y: 0, width: 17, height: 17)
                                v1.jq_borderWidth = 2
                                v1.jq_borderColor = .white
                                v1.jq_cornerRadius = 8.5
 
                                collectionView.collectionViewLayout = TestLeftRightCollectionViewFlowLayout(width: JQ_ScreenW, height: 213.5)
                                collectionView.delegate = self
                                collectionView.dataSource = self
                                collectionView.isPagingEnabled = false
                                collectionView.bounces = false
                                collectionView.showsHorizontalScrollIndicator = false
                                collectionView.register(UINib(nibName: "HomeRelaxVoiceCCell", bundle: nil), forCellWithReuseIdentifier: "_HomeRelaxVoiceCCell")
                                collectionView.contentInset = UIEdgeInsets(top: 0, left: 100 , bottom: 0, right: 100)
                }
 
                @objc func playBGMbackEnd(){
                                isPlaying = false
                                collectionView.reloadData()
                }
 
                @IBAction func setttingAction(_ sender: UIButton) {
                                if settingModel != nil{
                                                guard let index = playAtIndex else {return}
            Services.saveUserSceneMusic(id: items[index.row].id).subscribe(onNext: {[weak self]data in
                guard let weakSelf = self else { return }
                weakSelf.settingModel?.sceneMusicModel = weakSelf.items[index.row]
                UserDefaultSettingViewModel.saveSetting(weakSelf.settingModel!)
                UserViewModel.setSceneSwitch(state: weakSelf.sceneSwitch.isOn)
                alertSuccess(msg: "设置成功")
            }).disposed(by: disposeBag)
 
            if isFromFist{
                NotificationCenter.default.post(name: PlantGuideQuit_Noti, object: items[index.row])
                return
            }
 
            needPopRoot = true
            DispatchQueue.main.asyncAfter(delay: 1.0) {
                NotificationCenter.default.post(name: SetBGMSuccess_Noti, object: self.items[index.row])
            }
 
            if !(UserViewModel.getLoginInfo()?.accessToken.isEmpty ?? true){
                DispatchQueue.main.asyncAfter(delay: 0.6) {
                    NotificationCenter.default.post(name: PlantGuideQuit_Noti, object: self.items[index.row])
                    self.navigationController?.popViewController()
                }
            }else{
                DispatchQueue.main.asyncAfter(delay: 0.6) {
                    self.navigationController?.popViewController()
                }
            }
                                }
                }
 
                deinit{
                                NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
                }
}
 
extension BackgroundVoiceVC:UIScrollViewDelegate{
 
                func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
                                let p = CGPoint(x: collectionView.contentOffset.x + collectionView.frame.size.width / 2, y:0)
                                if let v = collectionView.indexPathForItem(at: p){
                                                playAtIndex = v
                                }
                }
}
 
extension BackgroundVoiceVC:UICollectionViewDelegate & UICollectionViewDataSource{
 
                func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                                playAtIndex = indexPath
                                let model = items[indexPath.row]
                                collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
 
        guard let URL = URL(string: model.audioFile.jq_urlEncoded()) else { return }
        checkCacheAudio(from: URL) {[unowned self] state, url in
            self.tempPlayer = AVPlayer(url: url)
            self.tempPlayer!.play()
            self.isPlaying = true
        }
                                collectionView.reloadData()
                }
 
                func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                                return items.count
                }
 
                func numberOfSections(in collectionView: UICollectionView) -> Int {
                                return 1
                }
 
                func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_HomeRelaxVoiceCCell", for: indexPath) as! HomeRelaxVoiceCCell
                                cell.contentView.backgroundColor = .jq_randomColor
                                cell.setModel(items[indexPath.row])
 
                                if isPlaying && indexPath == playAtIndex{
                                                cell.img_play.image = UIImage(named: "icon_play_purse")
                                }else{
                                                cell.img_play.image = UIImage(named: "icon_play")
                                }
                                return cell
                }
 
    internal func checkCacheAudio(from url: URL, completion: @escaping (Bool,URL) -> Void) {
 
        let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("BGMs")
 
        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 = URLSession.shared.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()
    }
}
 
extension BackgroundVoiceVC:UICollectionViewDelegateFlowLayout{
                func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                                return CGSize(width: 148.25, height: 213.45)
                }
}