PQStuckPointCuttingView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. //
  2. // PQStuckPointCuttingView.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2021/5/8.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. //
  8. import UIKit
  9. class PQStuckPointCuttingView: UIView {
  10. // 视频时长
  11. var videoDuration: CGFloat = 0
  12. var lastVideoDuration:CGFloat = 0
  13. // 卡点开始时间 默认 0
  14. var stuckPointStartTime: CGFloat = 0
  15. // 卡点结束时间
  16. var stuckPointEndTime: CGFloat = 0
  17. // 裁剪开始时间 默认 0
  18. private var cutStartTime: CGFloat = 0
  19. // /// 裁剪结束最终的开始时间
  20. // private var cutFinishedStartTime: CGFloat {
  21. // (scrollView.contentOffset.x / perSecondWidth) + (((scrollView.frame.width - videoCropView.frame.width) / 2 + 15) / perSecondWidth) + cutStartTime
  22. // }
  23. //
  24. // /// 裁剪结束最终的结束时间
  25. // private var cutFinishedEndTime: CGFloat {
  26. // cutFinishedStartTime + (cutEndTime - cutStartTime)
  27. // }
  28. // 播放进度
  29. private var videoProgress: CGFloat = 0
  30. // 最小时长 默认 10s
  31. private var minCutTime: CGFloat = 10
  32. /// 时间间隔
  33. private var timeRange: CGFloat = cDefaultMargin
  34. /// 刻度高
  35. private var rateHeight: CGFloat = 23
  36. /// 时间线宽
  37. private var timeLineWidth: CGFloat = 35
  38. /// 时间线间隔
  39. private var timeLineMargin: CGFloat = 35
  40. /// 时间线高
  41. private var timeHeight: CGFloat = cDefaultMargin * 4
  42. /// 频率线宽
  43. private var frequencyWidth: CGFloat = adapterWidth(width: 1.5)
  44. /// 频率间隔
  45. private var frequencyMargin: CGFloat = adapterWidth(width: 3)
  46. /// 竖线和contentview 父视图的左右间隔
  47. private var margin: CGFloat = (cScreenWidth - adapterWidth(width: 250)) / 2
  48. /// 滑动区域大小
  49. private var contentWidth: CGFloat = 0
  50. // 竖线一个间隔代表多少 S 是动态的
  51. private var oneMarginTime: CGFloat = 0
  52. private var isDrawLine: Bool = false
  53. // 保存已经绘制的竖线用于变色使用
  54. var lineLayerArray: Array = Array<CAShapeLayer>.init()
  55. // 裁剪区的相素大小
  56. var cropViewWidth: CGFloat = adapterWidth(width: 250)
  57. /// 拖拽改变实时的回调
  58. var videoRangeDidChanged: ((_ startTime: CGFloat, _ endTime: CGFloat) -> Void)?
  59. /// 进度改变实时的回调
  60. var videoProgressDidChanged: ((_ progress: CGFloat) -> Void)?
  61. /// 拖缀结束的回调 type - 1-拖动左边裁剪结束 2--拖动右边裁剪结束 3-进度条拖动结束 4-滑动结束
  62. var videoDidEndDragging: ((_ type: Int, _ startTime: CGFloat, _ endTime: CGFloat, _ progress: CGFloat) -> Void)?
  63. // 开始划动
  64. var videoDidBeginDrag: (() -> Void)?
  65. // 选择区内的线个数
  66. var wavSelectCount: Int = 0
  67. // 整首歌的线的个数
  68. var wavTotalCount: Int = 0
  69. //推荐虚线的位置
  70. var startLineX:CGFloat = 0.0
  71. //如果是用户主动划动的 就不自动滚动到推荐位置了
  72. var isUserDrag:Bool = false
  73. // 推荐卡点起始时间
  74. var suggestRhythmStartTime:CGFloat = 0.0
  75. var suggestRhythmEndTime:CGFloat = 0.0
  76. /// 滚动视图
  77. lazy var scrollView: UIScrollView = {
  78. let scrollView = UIScrollView(frame: bounds)
  79. scrollView.showsVerticalScrollIndicator = false
  80. scrollView.showsHorizontalScrollIndicator = false
  81. scrollView.bounces = false
  82. scrollView.delegate = self
  83. if #available(iOS 11.0, *) {
  84. scrollView.contentInsetAdjustmentBehavior = .never
  85. } else {
  86. // automaticallyAdjustsScrollViewInsets = false
  87. }
  88. scrollView.backgroundColor = .clear
  89. return scrollView
  90. }()
  91. //
  92. lazy var rateView: UIView = {
  93. let rateView = UIView(frame: CGRect(x: 0, y: 22, width: scrollView.contentSize.width, height: rateHeight))
  94. rateView.backgroundColor = .clear
  95. return rateView
  96. }()
  97. // 总时长
  98. lazy var tatalTimeLabel: UILabel = {
  99. let tatalTimeLabel = UILabel()
  100. tatalTimeLabel.font = UIFont.systemFont(ofSize: 11)
  101. tatalTimeLabel.textAlignment = .right
  102. tatalTimeLabel.tag = 66
  103. tatalTimeLabel.textColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  104. return tatalTimeLabel
  105. }()
  106. // 显示选择框
  107. lazy var videoCropView: UIView = {
  108. let videoCropView: UIView = UIView(frame: CGRect(x: (cScreenWidth - cropViewWidth) / 2, y: 0, width: cropViewWidth, height: 80))
  109. videoCropView.isUserInteractionEnabled = false
  110. videoCropView.layer.borderColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
  111. videoCropView.layer.borderWidth = 2
  112. videoCropView.layer.cornerRadius = 8
  113. return videoCropView
  114. }()
  115. //两边的mask 2 是裁剪区的边框
  116. lazy var leftMaskView: UIView = {
  117. let leftMaskView: UIView = UIView(frame: CGRect(x:0, y: 0, width: (cScreenWidth - cropViewWidth) / 2 - 2, height: 80))
  118. leftMaskView.backgroundColor = UIColor.white
  119. leftMaskView.alpha = 0.7
  120. return leftMaskView
  121. }()
  122. //右边的mask 2 是裁剪区的边框
  123. lazy var rightMaskView: UIView = {
  124. let rightMaskView: UIView = UIView(frame: CGRect(x:videoCropView.frame.maxX + 2, y: 0, width: (cScreenWidth - cropViewWidth) / 2, height: 80))
  125. rightMaskView.backgroundColor = UIColor.white
  126. rightMaskView.alpha = 0.7
  127. return rightMaskView
  128. }()
  129. private override init(frame: CGRect) {
  130. super.init(frame: frame)
  131. }
  132. required init?(coder _: NSCoder) {
  133. fatalError("init(coder:) has not been implemented")
  134. }
  135. init(frame: CGRect, duration: CGFloat, suggestRhythmStartTime: CGFloat) {
  136. super.init(frame: frame)
  137. videoDuration = duration
  138. self.suggestRhythmStartTime = suggestRhythmStartTime
  139. }
  140. /// 更新卡点值
  141. /// - Parameter endTime: endTime description
  142. /// - Returns: <#description#>
  143. func updateEndTime(startTime: CGFloat, endTime: CGFloat,
  144. suggestRhythmStartTime: CGFloat, suggestRhythmEndTime: CGFloat) {
  145. // videoDuration = duration
  146. self.suggestRhythmStartTime = suggestRhythmStartTime
  147. self.suggestRhythmEndTime = suggestRhythmEndTime
  148. startLineX = 0
  149. stuckPointStartTime = startTime
  150. stuckPointEndTime = endTime
  151. tatalTimeLabel.text = "\(Float64(stuckPointEndTime - stuckPointStartTime).formatDurationToHMS())"
  152. BFLog(1, message: "播放开始:\(stuckPointStartTime) 结束:\(stuckPointEndTime) 时长为:\(stuckPointEndTime - stuckPointStartTime); 音乐总时长为:\(videoDuration);推荐卡点开始:\(suggestRhythmStartTime) 结束:\(suggestRhythmEndTime)")
  153. backgroundColor = PQBFConfig.shared.styleBackGroundColor
  154. addSubview(scrollView)
  155. addSubview(videoCropView)
  156. addSubview(leftMaskView)
  157. addSubview(rightMaskView)
  158. videoCropView.addSubview(tatalTimeLabel)
  159. addData()
  160. videoCropView.frame = CGRect(x: (cScreenWidth - cropViewWidth) / 2, y: 0, width: cropViewWidth, height: 80)
  161. leftMaskView.frame = CGRect(x:0, y: 0, width: (cScreenWidth - cropViewWidth) / 2 - 2, height: 80)
  162. rightMaskView.frame = CGRect(x:videoCropView.frame.maxX + 2, y: 0, width: (cScreenWidth - cropViewWidth) / 2 - 2, height: 80)
  163. tatalTimeLabel.snp.remakeConstraints { make in
  164. make.width.equalTo(40)
  165. make.height.equalTo(15)
  166. make.top.equalTo(videoCropView.snp_top).offset(6)
  167. make.right.equalTo(videoCropView.snp_right).offset(-6)
  168. }
  169. }
  170. func addData() {
  171. // 1,选择区内的线个数 ,划动区域后 个数会变???
  172. wavSelectCount = Int(ceil((cropViewWidth - frequencyWidth) / (frequencyWidth + frequencyMargin)) + 1)
  173. cropViewWidth = CGFloat(wavSelectCount) * (frequencyWidth + frequencyMargin) + frequencyWidth
  174. margin = (cScreenWidth - cropViewWidth) / 2.0
  175. // 2竖线一个间隔代表多少 S 是动态的
  176. oneMarginTime = (stuckPointEndTime - stuckPointStartTime) / CGFloat(wavSelectCount)
  177. // 如果视频结束时间点大于歌曲有效结束点,则拼接推荐的时间段直到满足视频播放
  178. var videoDurationTemp = suggestRhythmEndTime
  179. while stuckPointEndTime > videoDurationTemp {
  180. videoDurationTemp += (suggestRhythmEndTime - suggestRhythmStartTime)
  181. }
  182. videoDuration = videoDurationTemp
  183. // 3,一共绘制的竖线个数
  184. wavTotalCount = Int(ceil(videoDuration / oneMarginTime) + 1)
  185. timeRange = oneMarginTime * 10
  186. // 显示时间 label 的个数 , -1 不够整倍数就不显示时间了
  187. let timeLabelCount = Int(wavTotalCount / 10)
  188. contentWidth = CGFloat(wavTotalCount - 1) * (frequencyWidth + frequencyMargin) + frequencyWidth + (cScreenWidth - cropViewWidth)
  189. if contentWidth < scrollView.frame.width {
  190. contentWidth = scrollView.frame.width
  191. }
  192. scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.height)
  193. BFLog(1, message: "框内个数:\(wavSelectCount), 总线条数:\(wavTotalCount), 框宽:\(cropViewWidth), 最终音乐时长:\(videoDuration)")
  194. scrollView.subviews.forEach { lable in
  195. if lable is UILabel && lable.tag != 66 {
  196. lable.removeFromSuperview()
  197. }
  198. }
  199. for index in 0 ... timeLabelCount {
  200. // scrollView.viewWithTag(100 + index)?.removeFromSuperview()
  201. let titleLab = UILabel(frame: CGRect(x: CGFloat(index) * (frequencyWidth + frequencyMargin) * 10 + margin - timeLineWidth / 2, y: rateView.frame.maxY, width: timeLineWidth, height: 30))
  202. titleLab.font = UIFont.systemFont(ofSize: 11)
  203. titleLab.textAlignment = .center
  204. titleLab.numberOfLines = 1
  205. titleLab.tag = 100 + index
  206. titleLab.backgroundColor = .clear
  207. titleLab.textColor = UIColor.hexColor(hexadecimal: "#999999")
  208. titleLab.text = "\(Float64(Int(CGFloat(index) * timeRange)).formatDurationToHMS())"
  209. scrollView.addSubview(titleLab)
  210. }
  211. if oneMarginTime > 0 {
  212. // 1,处理音频频率
  213. configVoiceFrequency()
  214. // 2,滚动到推荐位置
  215. if(!isUserDrag){
  216. scrollView.contentOffset = CGPoint(x: startLineX - margin, y: 0)
  217. }
  218. scrollView.addSubview(rateView)
  219. }
  220. }
  221. /// 处理音频频率
  222. /// - Returns: <#description#>
  223. func configVoiceFrequency() {
  224. // 整倍数
  225. let waveTotalCount = Int(wavTotalCount) / cFrequency.count
  226. // 余多少个未画的
  227. var remainder = Int(wavTotalCount % cFrequency.count)
  228. var totalWave: [CGFloat] = Array<CGFloat>.init()
  229. // 1,先画整倍数个竖线
  230. for _ in 0 ..< waveTotalCount {
  231. totalWave = totalWave + cFrequency
  232. }
  233. if remainder > cFrequency.count - 1 {
  234. remainder = cFrequency.count - 1
  235. }
  236. // 1,再画余数个竖线
  237. if remainder > 0 {
  238. totalWave = totalWave + cFrequency[0 ... (remainder - 1)]
  239. }
  240. createWave(waveArr: totalWave)
  241. }
  242. /// 更新进度绘制不同色值
  243. /// progress <#progress description#>
  244. func updateProgress(progress: CGFloat) {
  245. if(progress <= 0 || lineLayerArray.count == 0 || progress.isNaN){
  246. BFLog(message: "progress is error ")
  247. return
  248. }
  249. let startIndex = scrollView.contentOffset.x / (frequencyWidth + frequencyMargin)
  250. let selectIndex = Int(ceil(startIndex + progress * CGFloat(wavSelectCount)))
  251. if(selectIndex < lineLayerArray.count){
  252. let drawLayer:CAShapeLayer = lineLayerArray[selectIndex]
  253. // BFLog(1, message: "progress is \(progress) i \(selectIndex) 命中的位置:\(CGFloat(selectIndex) * oneMarginTime)")
  254. if drawLayer.strokeColor != UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor{
  255. drawLayer.strokeColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
  256. drawLayer.setNeedsDisplay()
  257. drawLayer.layoutIfNeeded()
  258. }
  259. }
  260. if(progress >= 0.999){
  261. BFLog(message: "播放完成 重新更新 UI ")
  262. resetDefaultsColor(clearData: false)
  263. }
  264. }
  265. // 竖线恢复到原有色值
  266. func resetDefaultsColor(clearData:Bool = true) {
  267. for layer in lineLayerArray {
  268. layer.strokeColor = UIColor.hexColor(hexadecimal: "#999999").cgColor
  269. layer.setNeedsDisplay()
  270. }
  271. if(clearData == true){
  272. lineLayerArray.removeAll()
  273. if(rateView.layer.sublayers != nil){
  274. for (_,layer) in rateView.layer.sublayers!.enumerated() {
  275. layer.removeFromSuperlayer()
  276. }
  277. }
  278. isUserDrag = false
  279. isDrawLine = false
  280. }
  281. }
  282. /// 生成波纹
  283. /// - Parameter waveArr: <#waveArr description#>
  284. /// - Returns: <#description#>
  285. func createWave(waveArr: [CGFloat]) {
  286. for (i, power) in waveArr.enumerated() {
  287. // 画布高度
  288. let hight: CGFloat = rateView.frame.height
  289. // 开始 Y 值
  290. var startY: CGFloat = (hight - power) / 2.0
  291. if startY < 0 { startY = 0 }
  292. // 结束 Y 值
  293. var endY: CGFloat = startY + power
  294. if endY > CGFloat(hight) { endY = hight }
  295. // 线的路径
  296. let linePath = UIBezierPath()
  297. // 起点 timeLineWidth / 2 处理显示时间的 label中心为时间点
  298. let originX: CGFloat = CGFloat(Float(i) * Float(frequencyWidth + frequencyMargin)) + margin
  299. linePath.move(to: CGPoint(x: originX, y: startY))
  300. // 终点
  301. linePath.addLine(to: CGPoint(x: originX, y: endY))
  302. let lineLayer = CAShapeLayer()
  303. lineLayer.lineWidth = frequencyWidth
  304. lineLayer.strokeColor = UIColor.hexColor(hexadecimal: "#999999").cgColor
  305. lineLayer.path = linePath.cgPath
  306. lineLayer.fillColor = UIColor.black.cgColor
  307. // 推荐的开始起点是虚线 减0.0001因为精度问题
  308. // BFLog(1, message: "suggestRhythmStartTime is \(suggestRhythmStartTime)")
  309. if oneMarginTime * CGFloat(i) >= (suggestRhythmStartTime-0.0001) && !isDrawLine {
  310. isDrawLine = true
  311. linePath.move(to: CGPoint(x: originX, y: -10))
  312. // 终点
  313. linePath.addLine(to: CGPoint(x: originX, y: 30))
  314. lineLayer.path = linePath.cgPath
  315. lineLayer.lineDashPhase = 0
  316. lineLayer.lineDashPattern = [3, 3]
  317. }
  318. if startLineX == 0 && oneMarginTime * CGFloat(i) >= stuckPointStartTime{
  319. startLineX = originX
  320. }
  321. lineLayerArray.append(lineLayer)
  322. rateView.layer.insertSublayer(lineLayer, at: 0)
  323. }
  324. }
  325. deinit {
  326. BFLog(message: "卡点裁剪-裁剪视图销毁")
  327. }
  328. //划动结速后处理
  329. func moveEnd() {
  330. //最后一个竖线VIEW
  331. let lastLine:UIView = scrollView.viewWithTag(100 + Int(videoDuration / timeRange) - 1) ?? UIView.init()
  332. //移动后的开始时间
  333. let startTime = videoDuration / lastLine.frame.maxX * scrollView.contentOffset.x
  334. // let startTime = videoDuration * (margin + scrollView.contentOffset.x) / scrollView.contentSize.width
  335. //选中的时长
  336. let selectDuration:CGFloat = CGFloat(stuckPointEndTime - stuckPointStartTime)
  337. BFLog(message: "拖拽结束 - 回调\(scrollView.contentOffset) \(scrollView.contentSize) 开始时间为:\(startTime) 结束时间为:\(startTime + selectDuration)")
  338. stuckPointStartTime = startTime
  339. stuckPointEndTime = stuckPointStartTime + selectDuration
  340. if(videoDidEndDragging != nil){
  341. videoDidEndDragging!(1,startTime,startTime + CGFloat(stuckPointEndTime - stuckPointStartTime),0)
  342. }
  343. resetDefaultsColor(clearData: false)
  344. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicPeriodSelect, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  345. }
  346. }
  347. // MARK: - scrollView滑动代理
  348. /// scrollView滑动代理
  349. extension PQStuckPointCuttingView: UIScrollViewDelegate {
  350. func scrollViewDidScroll(_: UIScrollView) {}
  351. func scrollViewWillBeginDragging(_ :UIScrollView){
  352. isUserDrag = true
  353. if(videoDidBeginDrag != nil){
  354. videoDidBeginDrag!()
  355. }
  356. }
  357. func scrollViewDidEndDecelerating(_: UIScrollView) {
  358. if !scrollView.isDragging, !scrollView.isDecelerating {
  359. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
  360. self?.moveEnd()
  361. }
  362. }
  363. }
  364. func scrollViewDidEndDragging(_:UIScrollView,willDecelerate decelerate:Bool){
  365. if !decelerate, !scrollView.isDragging, !scrollView.isDecelerating {
  366. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
  367. self?.moveEnd()
  368. }
  369. }
  370. }
  371. func scrollViewDidEndScrollingAnimation(_: UIScrollView) {
  372. BFLog(message: "scrollViewDidEndScrollingAnimation")
  373. }
  374. }