BFChooseMusicView.swift 17 KB

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