BFChooseMusicView.swift 16 KB

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