BFChooseMusicView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. //
  2. // BFChooseMusicView.swift
  3. // BFRecordScreenKit
  4. //
  5. // Created by 胡志强 on 2022/2/28.
  6. //
  7. import Foundation
  8. import UIKit
  9. import BFUIKit
  10. import BFMediaKit
  11. import BFCommonKit
  12. import BFNetRequestKit
  13. enum BFChooseMusicViewClickType {
  14. case sure, cancle, search
  15. }
  16. class BFChooseMusicView: UIView {
  17. var clickBtnAction: ((BFChooseMusicViewClickType) -> Void)?
  18. var cutActionCallback: ((PQVoiceModel) -> Void)?
  19. // 各类别音乐列表,以类别id为key
  20. var musicDic = [Int64 : [PQVoiceModel]]()
  21. var searchModel : PQVoiceModel?{
  22. willSet{
  23. if searchModel != nil {
  24. if let catogory = categories.first(where: { mod in
  25. mod.tagName == "热门"
  26. }){
  27. if let tid = catogory.tagId, let _ = musicDic[tid] {
  28. // 找到热门的数组
  29. musicDic[tid]?.removeFirst()
  30. }
  31. }
  32. }
  33. }
  34. didSet {
  35. if let searchModel = searchModel {
  36. if let catogory = categories.first(where: { mod in
  37. mod.tagName == "热门"
  38. }){
  39. if let tid = catogory.tagId, let list = musicDic[tid] {
  40. var arr = [PQVoiceModel]()
  41. arr.append(searchModel)
  42. if list.first?.musicId != searchModel.musicId {
  43. arr.append(contentsOf: list)
  44. musicDic[tid] = arr
  45. searchModel.isSelected = true
  46. chosedMusic?.isSelected = false
  47. chosedMusic = searchModel
  48. musicTb.reloadData()
  49. }
  50. }
  51. }
  52. }
  53. }
  54. }
  55. // 选择的音乐类别
  56. var categorySelectIndex : Int = 1
  57. // 音乐类别
  58. var categories = [PQStuckPointMusicTagsModel]()
  59. var musicVolume = 0.0 {
  60. didSet{
  61. slidV.value = Float(musicVolume)
  62. uiForChangeVolume()
  63. }
  64. }
  65. // 选中的音乐
  66. var chosedMusic : PQVoiceModel?
  67. var chosedIndexPath : IndexPath?
  68. var chosedCellStatu : BFMuicInfoCellState = .pause
  69. var loadedTimeRangesObserver : NSKeyValueObservation?
  70. // 试听音乐
  71. let player:AVPlayer = {
  72. let p = AVPlayer(playerItem: nil)
  73. return p
  74. }()
  75. lazy var categoryView : UICollectionView = {
  76. let layout = BFCollectionViewFlowLayout()
  77. layout.dele = self
  78. layout.scrollDirection = .horizontal
  79. layout.minimumLineSpacing = 25
  80. // layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
  81. layout.minimumInteritemSpacing = 2
  82. let vv = UICollectionView(frame: CGRect(x: 60, y: 0, width: cScreenWidth - 60, height: 40), collectionViewLayout: layout)
  83. vv.isPagingEnabled = false
  84. vv.showsHorizontalScrollIndicator = false
  85. vv.showsVerticalScrollIndicator = false
  86. vv.register(BFMusicCategoryCell.self, forCellWithReuseIdentifier: "BFMusicCategoryCell")
  87. vv.backgroundColor = UIColor.clear
  88. vv.delegate = self
  89. vv.dataSource = self
  90. if #available(iOS 11.0, *) {
  91. vv.contentInsetAdjustmentBehavior = .never
  92. } else {
  93. // Fallback on earlier versions
  94. }
  95. vv.backgroundColor = .clear
  96. return vv
  97. }()
  98. lazy var progressL : UILabel = {
  99. let l = UILabel()
  100. l.textColor = UIColor.hexColor(hexadecimal: "#9d9d9d")
  101. l.font = UIFont.systemFont(ofSize: 13, weight: .regular)
  102. l.textAlignment = .center
  103. l.text = "0%"
  104. return l
  105. }()
  106. lazy var slidV : UISlider = {
  107. let v = UISlider()
  108. v.addTarget(self, action: #selector(valuChange(slid:)), for: .valueChanged)
  109. return v
  110. }()
  111. lazy var musicTb : UITableView = {
  112. let tb = UITableView(frame: .zero)
  113. tb.delegate = self
  114. tb.dataSource = self
  115. tb.separatorColor = UIColor.hexColor(hexadecimal: "#272727")
  116. tb.register(BFMuicInfoCell.self, forCellReuseIdentifier: "BFMuicInfoCell")
  117. tb.tableFooterView = UIView()
  118. tb.backgroundColor = .clear
  119. return tb
  120. }()
  121. override init(frame: CGRect) {
  122. super.init(frame: frame)
  123. backgroundColor = UIColor.clear
  124. let dismisBtn = UIButton()
  125. dismisBtn.tag = 1004
  126. dismisBtn.frame = CGRect(x: 0, y: 0, width: width, height: 200)
  127. dismisBtn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
  128. addSubview(dismisBtn)
  129. let backV = UIView()
  130. backV.backgroundColor = .black
  131. backV.isUserInteractionEnabled = true
  132. backV.layer.cornerRadius = 10
  133. backV.frame = CGRect(x: 0, y: 200, width: cScreenWidth, height: cScreenHeigth - 190)
  134. addSubview(backV)
  135. let cancelBtn = UIButton()
  136. cancelBtn.tag = 1001
  137. cancelBtn.frame = CGRect(x: 18, y: 227, width: 35, height: 24)
  138. cancelBtn.setTitle("取消", for: .normal)
  139. cancelBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#616161"), for: .normal)
  140. cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
  141. cancelBtn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
  142. addSubview(cancelBtn)
  143. let sureBtn = UIButton()
  144. sureBtn.tag = 1002
  145. sureBtn.frame = CGRect(x: width - 35 - 18, y: 227, width: 35, height: 24)
  146. sureBtn.setTitle("确定", for: .normal)
  147. sureBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#389AFF"), for: .normal)
  148. sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
  149. sureBtn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
  150. addSubview(sureBtn)
  151. let line1 = UIView()
  152. line1.backgroundColor = UIColor.hexColor(hexadecimal: "#272727")
  153. line1.frame = CGRect(x: 0, y: 260, width: width, height: 1)
  154. addSubview(line1)
  155. categoryView.frame = CGRect(x: 0, y: line1.bottomY, width: width - 50, height: 40)
  156. addSubview(categoryView)
  157. let searchBtn = UIButton()
  158. searchBtn.tag = 1003
  159. searchBtn.frame = CGRect(x: categoryView.rightX+2, y: line1.bottomY, width: 40, height: 40)
  160. searchBtn.setImage(imageInRecordScreenKit(by: "search"), for: .normal)
  161. searchBtn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
  162. addSubview(searchBtn)
  163. let line2 = UIView()
  164. line2.backgroundColor = UIColor.hexColor(hexadecimal: "#272727")
  165. line2.frame = CGRect(x: 0, y: categoryView.bottomY, width: width, height: 1)
  166. addSubview(line2)
  167. musicTb.frame = CGRect(x: 0, y: line2.bottomY, width: width, height: height - line2.bottomY - 100)
  168. addSubview(musicTb)
  169. let soundIV = UIImageView(image: imageInRecordScreenKit(by: "soundBtn"))
  170. soundIV.frame = CGRect(x: 16, y: musicTb.bottomY + 36, width: 28, height: 28)
  171. soundIV.contentMode = .scaleAspectFit
  172. addSubview(soundIV)
  173. slidV.frame = CGRect(x: soundIV.rightX + 20, y: soundIV.y+5, width: cScreenWidth - soundIV.rightX - 20 - 18, height: 18)
  174. addSubview(slidV)
  175. progressL.frame = CGRect(x: slidV.x - 7, y: slidV.y - 24, width: 36, height: 16)
  176. addSubview(progressL)
  177. self.musicVolume = 0.2
  178. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main) {[weak self] notice in
  179. guard let wself = self else { return }
  180. wself.choseCell()?.status = .pause
  181. wself.chosedCellStatu = .pause
  182. }
  183. loadedTimeRangesObserver = player.observe(\AVPlayer.currentItem?.loadedTimeRanges, options: [.new, .initial]) { [weak self] (player, change) in
  184. DispatchQueue.main.async {[weak self] in
  185. guard let wself = self else { return }
  186. guard let ranges = change.newValue as? [CMTimeRange] else { return }
  187. if let indx = wself.chosedIndexPath, let cell = wself.musicTb.cellForRow(at: indx) as? BFMuicInfoCell, let totalDur = player.currentItem?.duration, totalDur.isValid, CMTimeCompare(ranges.first?.duration ?? .zero, totalDur) >= 0{
  188. if (player.currentItem?.asset as? AVURLAsset)?.url.absoluteString ?? "b" == cell.data?.musicPath ?? "a" {
  189. if cell.status != .playing{
  190. cell.status = .playing
  191. wself.chosedCellStatu = .playing
  192. }
  193. }
  194. }
  195. BFLog(1, message: "开始播放音乐:\(ranges.first?.start.seconds ?? 0), dur:\( ranges.first?.duration.seconds ?? 0), tot:\(player.currentItem?.duration.seconds ?? 0)")
  196. }
  197. }
  198. prepareData()
  199. }
  200. required init?(coder: NSCoder) {
  201. fatalError("init(coder:) has not been implemented")
  202. }
  203. func prepareData() {
  204. BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointMusicCategoryUrl, parames: ["parentTagId": 0], commonParams: commonParams(), isJsonEncodingNormal: true, timeoutInterval: 15) {[weak self] response, _, error, _ in
  205. guard let wself = self else { return }
  206. var tagsList = Array<PQStuckPointMusicTagsModel>.init()
  207. if response is NSNull || response == nil {
  208. cShowHUB(superView: nil, msg: "音乐分类获取失败")
  209. return
  210. }
  211. let tagsTempArr = response as? [[String: Any]]
  212. if tagsTempArr != nil, (tagsTempArr?.count ?? 0) > 0 {
  213. for dict in tagsTempArr! {
  214. let tempMusic = PQStuckPointMusicTagsModel(jsonDict: dict)
  215. tempMusic.parentTagId = 0
  216. tagsList.append(tempMusic)
  217. }
  218. }
  219. tagsList.first?.isSelected = true
  220. let tempMusic = PQStuckPointMusicTagsModel()
  221. tempMusic.tagId = -1
  222. tagsList.insert(tempMusic, at: 0)
  223. wself.categories.append(contentsOf: tagsList)
  224. wself.categoryView.reloadData()
  225. if wself.categories.count > 1 {
  226. wself.categorySelectIndex = 1
  227. if let firstTagid = wself.categories[1].tagId{
  228. wself.getMusicsForCategory(tagId:firstTagid, pageNum: 1)
  229. }
  230. }
  231. }
  232. }
  233. func getMusicsForCategory(tagId:Int64, pageNum:Int64) {
  234. BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointMusicPageUrl, parames: ["tagId": tagId, "parentTagId": 0, "pageNum": pageNum, "pageSize": 20], commonParams: commonParams()) {[weak self] response, _, error, _ in
  235. guard let wself = self else { return }
  236. var musicPageList = [PQVoiceModel]()
  237. if response is NSNull || response == nil {
  238. cShowHUB(superView: nil, msg: "该分类下无音乐")
  239. return
  240. }
  241. if wself.musicDic[tagId] == nil {
  242. wself.musicDic[tagId] = [PQVoiceModel]()
  243. }
  244. let oldDataMusic : [PQVoiceModel] = wself.musicDic[tagId]!
  245. if let tempArr = response as? [[String: Any]], tempArr.count > 0 {
  246. for (_, dict) in tempArr.enumerated() {
  247. let tempMusic = PQVoiceModel(jsonDict: dict)
  248. tempMusic.cacheTagID = tagId
  249. if tempMusic.endTime <= tempMusic.startTime {
  250. tempMusic.endTime = tempMusic.startTime + 40
  251. }
  252. let haveIndex = oldDataMusic.firstIndex(where: { (music) -> Bool in
  253. music.musicId == tempMusic.musicId
  254. })
  255. if haveIndex == nil {
  256. musicPageList.append(tempMusic)
  257. }
  258. }
  259. }
  260. if musicPageList.count > 0 {
  261. wself.musicDic[tagId]!.append(contentsOf: musicPageList)
  262. if tagId == wself.categories[wself.categorySelectIndex].tagId{
  263. wself.musicTb.reloadData()
  264. }
  265. }
  266. }
  267. }
  268. @objc func valuChange(slid:UISlider) {
  269. musicVolume = Double(slid.value)
  270. }
  271. func uiForChangeVolume() {
  272. let num = (Int)(musicVolume * 100)
  273. progressL.text = String(format: "%d%%", num)
  274. var frame = progressL.frame
  275. frame.origin.x = slidV.x - 7 + ((slidV.width - 28) / 100.0) * CGFloat(num)
  276. progressL.frame = frame
  277. player.volume = Float(musicVolume)
  278. chosedMusic?.volume = num
  279. }
  280. func configCategoriesView(){
  281. categoryView.reloadData()
  282. }
  283. func choseCell() -> BFMuicInfoCell? {
  284. if let indpx = chosedIndexPath, let cell = musicTb.cellForRow(at: indpx) as? BFMuicInfoCell {
  285. return cell
  286. }
  287. return nil
  288. }
  289. @objc func btnAction(btn:UIButton) {
  290. player.pause()
  291. choseCell()?.status = .pause
  292. switch btn.tag{
  293. case 1001:
  294. clickBtnAction?(.cancle)
  295. case 1002, 1004:
  296. clickBtnAction?(.sure)
  297. case 1003:
  298. clickBtnAction?(.search)
  299. default:break
  300. }
  301. }
  302. func reloadView() {
  303. }
  304. // 取消选歌
  305. func cancelChooseMusic() {
  306. chosedMusic = nil
  307. player.pause()
  308. choseCell()?.changeSelected(false)
  309. }
  310. }
  311. extension BFChooseMusicView:UITableViewDelegate, UITableViewDataSource {
  312. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  313. let cell = tableView.dequeueReusableCell(withIdentifier: "BFMuicInfoCell", for: indexPath) as! BFMuicInfoCell
  314. cell.selectionStyle = .none
  315. cell.cutCallBack = {[weak self, weak cell] in
  316. guard let wself = self else { return }
  317. wself.player.pause()
  318. if let data = cell?.data {
  319. wself.cutActionCallback?(data)
  320. }
  321. }
  322. if let tagid = categories[categorySelectIndex].tagId, let arr = musicDic[tagid] {
  323. cell.data = arr[indexPath.row]
  324. if cell.data?.isSelected ?? false {
  325. chosedIndexPath = indexPath
  326. chosedMusic = cell.data
  327. cell.status = chosedCellStatu
  328. }else{
  329. cell.status = .normal
  330. }
  331. }
  332. return cell
  333. }
  334. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  335. return 64
  336. }
  337. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  338. if categories.count > 1 {
  339. return musicDic[categories[categorySelectIndex].tagId ?? 0]?.count ?? 0
  340. }
  341. return 0
  342. }
  343. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  344. if let cell = tableView.cellForRow(at: indexPath) as? BFMuicInfoCell {
  345. chosedMusic?.isSelected = false
  346. chosedMusic = cell.data
  347. chosedMusic?.isSelected = true
  348. cell.changeSelected(true)
  349. chosedIndexPath = indexPath
  350. if cell.status == .normal {
  351. if let urlStr = cell.data?.musicPath, let url = URL(string: urlStr){
  352. BFLog(1, message: "歌曲地址: \(url)")
  353. if url.absoluteString != (player.currentItem?.asset as? AVURLAsset)?.url.absoluteString ?? "b" {
  354. player.replaceCurrentItem(with: AVPlayerItem(url: url))
  355. cell.status = .loading
  356. }else {
  357. cell.status = .playing
  358. }
  359. player.play()
  360. }
  361. }else if cell.status == .pause{
  362. player.play()
  363. } else{
  364. player.pause()
  365. cell.status = .pause
  366. }
  367. chosedCellStatu = cell.status
  368. }
  369. }
  370. func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
  371. let cell = tableView.cellForRow(at: indexPath) as? BFMuicInfoCell
  372. cell?.status = .normal
  373. cell?.changeSelected(false)
  374. chosedIndexPath = nil
  375. player.pause()
  376. }
  377. }
  378. extension BFChooseMusicView : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
  379. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  380. return categories.count
  381. }
  382. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  383. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BFMusicCategoryCell", for: indexPath) as! BFMusicCategoryCell
  384. cell.addData(dic: categories[indexPath.row])
  385. cell.isChoosed = (indexPath.row == categorySelectIndex)
  386. return cell
  387. }
  388. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  389. let oldCell = collectionView.cellForItem(at: IndexPath(row: categorySelectIndex, section: 0)) as? BFMusicCategoryCell
  390. let newCell = collectionView.cellForItem(at: indexPath) as? BFMusicCategoryCell
  391. if indexPath.row > 0 {
  392. categorySelectIndex = indexPath.row
  393. musicTb.reloadData()
  394. oldCell?.isChoosed = false
  395. newCell?.isChoosed = true
  396. getMusicsForCategory(tagId: categories[categorySelectIndex].tagId ?? 0, pageNum: 1)
  397. }else {
  398. cancelChooseMusic()
  399. }
  400. }
  401. }
  402. extension BFChooseMusicView: BFFlowLayoutDelegate{
  403. func flowLayout(_ flowLayout: BFCollectionViewFlowLayout, itemHeight indexPath: IndexPath) -> CGFloat {
  404. var itemWidth = 30.0
  405. if let title = categories[indexPath.row].tagName, title.count > 0{
  406. let ww = title.textAutoWidth(height: 20, font: UIFont.systemFont(ofSize: 15, weight: .regular))
  407. itemWidth = max(30.0, ww)
  408. }
  409. return itemWidth
  410. }
  411. }
  412. extension String{
  413. func textAutoWidth(height:CGFloat, font:UIFont) ->CGFloat{
  414. let string = self as NSString
  415. let origin = NSStringDrawingOptions.usesLineFragmentOrigin
  416. let lead = NSStringDrawingOptions.usesFontLeading
  417. let rect = string.boundingRect(with:CGSize(width:0, height: height), options: [origin,lead],
  418. attributes: [NSAttributedString.Key.font:font],
  419. context:nil)
  420. return rect.width
  421. }
  422. }