杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
XQMuse/Root/Home/VC/BackgroundVoiceVC.swift
@@ -107,9 +107,6 @@
                        v1.jq_borderColor = .white
                        v1.jq_cornerRadius = 8.5
//                        slider_voice.setThumbImage(v1.qmui_snapshotLayerImage(), for: .normal)
//                        slider_voice.setThumbImage(v1.qmui_snapshotLayerImage(), for: .highlighted)
                        collectionView.collectionViewLayout = TestLeftRightCollectionViewFlowLayout(width: JQ_ScreenW, height: 213.5)
                        collectionView.delegate = self
                        collectionView.dataSource = self
@@ -182,11 +179,11 @@
                        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        guard let URL = URL(string: model.audioFile.jq_urlEncoded()) else { return }
                        tempPlayer = AVPlayer(url: URL)
//                        tempPlayer?.volume = slider_voice.value
                        tempPlayer!.play()
                        isPlaying = true
        checkCacheAudio(from: URL) {[unowned self] state, url in
            self.tempPlayer = AVPlayer(url: url)
            self.tempPlayer!.play()
            self.isPlaying = true
        }
                        collectionView.reloadData()
            }
@@ -210,6 +207,45 @@
                        }
                        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{