BFChooseMusicView.swift 15 KB

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