PQStuckPointCuttingView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. /// 滚动视图
  76. lazy var scrollView: UIScrollView = {
  77. let scrollView = UIScrollView(frame: bounds)
  78. scrollView.showsVerticalScrollIndicator = false
  79. scrollView.showsHorizontalScrollIndicator = false
  80. scrollView.bounces = false
  81. scrollView.delegate = self
  82. if #available(iOS 11.0, *) {
  83. scrollView.contentInsetAdjustmentBehavior = .never
  84. } else {
  85. // automaticallyAdjustsScrollViewInsets = false
  86. }
  87. scrollView.backgroundColor = .clear
  88. return scrollView
  89. }()
  90. //
  91. lazy var rateView: UIView = {
  92. let rateView = UIView(frame: CGRect(x: 0, y: 22, width: scrollView.contentSize.width, height: rateHeight))
  93. rateView.backgroundColor = .clear
  94. return rateView
  95. }()
  96. // 总时长
  97. lazy var tatalTimeLabel: UILabel = {
  98. let tatalTimeLabel = UILabel()
  99. tatalTimeLabel.font = UIFont.systemFont(ofSize: 11)
  100. tatalTimeLabel.textAlignment = .right
  101. tatalTimeLabel.tag = 66
  102. tatalTimeLabel.textColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  103. return tatalTimeLabel
  104. }()
  105. // 显示选择框
  106. lazy var videoCropView: UIView = {
  107. let videoCropView: UIView = UIView(frame: CGRect(x: (cScreenWidth - cropViewWidth) / 2, y: 0, width: cropViewWidth, height: 80))
  108. videoCropView.isUserInteractionEnabled = false
  109. videoCropView.layer.borderColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
  110. videoCropView.layer.borderWidth = 2
  111. videoCropView.layer.cornerRadius = 8
  112. return videoCropView
  113. }()
  114. //两边的mask 2 是裁剪区的边框
  115. lazy var leftMaskView: UIView = {
  116. let leftMaskView: UIView = UIView(frame: CGRect(x:0, y: 0, width: (cScreenWidth - cropViewWidth) / 2 - 2, height: 80))
  117. leftMaskView.backgroundColor = UIColor.white
  118. leftMaskView.alpha = 0.7
  119. return leftMaskView
  120. }()
  121. //右边的mask 2 是裁剪区的边框
  122. lazy var rightMaskView: UIView = {
  123. let rightMaskView: UIView = UIView(frame: CGRect(x:videoCropView.frame.maxX + 2, y: 0, width: (cScreenWidth - cropViewWidth) / 2, height: 80))
  124. rightMaskView.backgroundColor = UIColor.white
  125. rightMaskView.alpha = 0.7
  126. return rightMaskView
  127. }()
  128. private override init(frame: CGRect) {
  129. super.init(frame: frame)
  130. }
  131. required init?(coder _: NSCoder) {
  132. fatalError("init(coder:) has not been implemented")
  133. }
  134. init(frame: CGRect, duration: CGFloat, suggestRhythmStartTime: CGFloat) {
  135. super.init(frame: frame)
  136. videoDuration = duration
  137. self.suggestRhythmStartTime = suggestRhythmStartTime
  138. }
  139. /// 更新卡点值
  140. /// - Parameter endTime: endTime description
  141. /// - Returns: <#description#>
  142. func updateEndTime(startTime: CGFloat, endTime: CGFloat) {
  143. stuckPointStartTime = startTime
  144. stuckPointEndTime = endTime
  145. tatalTimeLabel.text = "\(Float64(stuckPointEndTime - stuckPointStartTime).formatDurationToHMS())"
  146. BFLog(1, message: "推荐开始\(stuckPointStartTime) 结束\(stuckPointEndTime) 时长为:\(stuckPointEndTime - stuckPointStartTime) 音乐总时长为:\(videoDuration)")
  147. backgroundColor = PQBFConfig.shared.styleBackGroundColor
  148. addSubview(scrollView)
  149. addSubview(videoCropView)
  150. addSubview(leftMaskView)
  151. addSubview(rightMaskView)
  152. videoCropView.addSubview(tatalTimeLabel)
  153. addData()
  154. videoCropView.frame = CGRect(x: (cScreenWidth - cropViewWidth) / 2, y: 0, width: cropViewWidth, height: 80)
  155. tatalTimeLabel.snp.remakeConstraints { make in
  156. make.width.equalTo(40)
  157. make.height.equalTo(15)
  158. make.top.equalTo(videoCropView.snp_top).offset(6)
  159. make.right.equalTo(videoCropView.snp_right).offset(-6)
  160. }
  161. }
  162. func addData() {
  163. // 1,选择区内的线个数 ,划动区域后 个数会变???
  164. wavSelectCount = Int(ceil((cropViewWidth - frequencyWidth) / (frequencyWidth + frequencyMargin)) + 1)
  165. cropViewWidth = CGFloat(wavSelectCount - 1) * (frequencyWidth + frequencyMargin) + frequencyWidth
  166. // 2竖线一个间隔代表多少 S 是动态的
  167. oneMarginTime = (stuckPointEndTime - stuckPointStartTime) / CGFloat(wavSelectCount - 1)
  168. // 3,一共绘制的竖线个数
  169. wavTotalCount = Int(ceil(videoDuration / oneMarginTime) + 1)
  170. timeRange = oneMarginTime * 10
  171. // 显示时间 label 的个数 , -1 不够整倍数就不显示时间了
  172. let timeLabelCount = Int(wavTotalCount / 10)
  173. contentWidth = CGFloat(wavTotalCount - 1) * (frequencyWidth + frequencyMargin) + frequencyWidth + (cScreenWidth - cropViewWidth)
  174. if contentWidth < scrollView.frame.width {
  175. contentWidth = scrollView.frame.width
  176. }
  177. scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.height)
  178. BFLog(1, message: "框内个数:\(wavSelectCount), 总线条数:\(wavTotalCount), 框宽:\(cropViewWidth)")
  179. scrollView.subviews.forEach { lable in
  180. if lable is UILabel && lable.tag != 66 {
  181. lable.removeFromSuperview()
  182. }
  183. }
  184. for index in 0 ... timeLabelCount {
  185. // scrollView.viewWithTag(100 + index)?.removeFromSuperview()
  186. let titleLab = UILabel(frame: CGRect(x: CGFloat(index) * (frequencyWidth + frequencyMargin) * 10 + margin - timeLineWidth / 2, y: rateView.frame.maxY, width: timeLineWidth, height: 30))
  187. titleLab.font = UIFont.systemFont(ofSize: 11)
  188. titleLab.textAlignment = .center
  189. titleLab.numberOfLines = 1
  190. titleLab.tag = 100 + index
  191. titleLab.backgroundColor = .clear
  192. titleLab.textColor = UIColor.hexColor(hexadecimal: "#999999")
  193. titleLab.text = "\(Float64(Int(CGFloat(index) * timeRange)).formatDurationToHMS())"
  194. scrollView.addSubview(titleLab)
  195. }
  196. if oneMarginTime > 0 {
  197. // 1,处理音频频率
  198. configVoiceFrequency()
  199. // 2,滚动到推荐位置
  200. if(!isUserDrag){
  201. scrollView.contentOffset = CGPoint(x: startLineX - margin, y: 0)
  202. }
  203. scrollView.addSubview(rateView)
  204. }
  205. }
  206. /// 处理音频频率
  207. /// - Returns: <#description#>
  208. func configVoiceFrequency() {
  209. // 整倍数
  210. let waveTotalCount = Int(wavTotalCount) / cFrequency.count
  211. // 余多少个未画的
  212. var remainder = Int(wavTotalCount % cFrequency.count)
  213. var totalWave: [CGFloat] = Array<CGFloat>.init()
  214. // 1,先画整倍数个竖线
  215. for _ in 0 ..< waveTotalCount {
  216. totalWave = totalWave + cFrequency
  217. }
  218. if remainder > cFrequency.count - 1 {
  219. remainder = cFrequency.count - 1
  220. }
  221. // 1,再画余数个竖线
  222. if remainder > 0 {
  223. totalWave = totalWave + cFrequency[0 ... (remainder - 1)]
  224. }
  225. createWave(waveArr: totalWave)
  226. }
  227. /// 更新进度绘制不同色值
  228. /// progress <#progress description#>
  229. func updateProgress(progress: CGFloat) {
  230. if(progress <= 0 || lineLayerArray.count == 0 || progress.isNaN){
  231. BFLog(message: "progress is error ")
  232. return
  233. }
  234. let startIndex = scrollView.contentOffset.x / (frequencyWidth + frequencyMargin)
  235. let selectIndex = Int(floor(startIndex + progress * CGFloat(wavSelectCount)))
  236. if(selectIndex < lineLayerArray.count){
  237. let drawLayer:CAShapeLayer = lineLayerArray[selectIndex]
  238. BFLog(message: "progress is \(progress) i \(selectIndex) 命中的位置:\(CGFloat(selectIndex) * oneMarginTime)")
  239. if drawLayer.strokeColor != UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor{
  240. drawLayer.strokeColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
  241. drawLayer.setNeedsDisplay()
  242. }
  243. }
  244. if(progress >= 0.99){
  245. BFLog(message: "播放完成 重新更新 UI ")
  246. resetDefaultsColor(clearData: false)
  247. }
  248. }
  249. // 竖线恢复到原有色值
  250. func resetDefaultsColor(clearData:Bool = true) {
  251. for layer in lineLayerArray {
  252. layer.strokeColor = UIColor.hexColor(hexadecimal: "#999999").cgColor
  253. layer.setNeedsDisplay()
  254. }
  255. if(clearData == true){
  256. lineLayerArray.removeAll()
  257. if(rateView.layer.sublayers != nil){
  258. for (_,layer) in rateView.layer.sublayers!.enumerated() {
  259. layer.removeFromSuperlayer()
  260. }
  261. }
  262. isUserDrag = false
  263. isDrawLine = false
  264. }
  265. }
  266. /// 生成波纹
  267. /// - Parameter waveArr: <#waveArr description#>
  268. /// - Returns: <#description#>
  269. func createWave(waveArr: [CGFloat]) {
  270. for (i, power) in waveArr.enumerated() {
  271. // 画布高度
  272. let hight: CGFloat = rateView.frame.height
  273. // 开始 Y 值
  274. var startY: CGFloat = (hight - power) / 2.0
  275. if startY < 0 { startY = 0 }
  276. // 结束 Y 值
  277. var endY: CGFloat = startY + power
  278. if endY > CGFloat(hight) { endY = hight }
  279. // 线的路径
  280. let linePath = UIBezierPath()
  281. // 起点 timeLineWidth / 2 处理显示时间的 label中心为时间点
  282. let originX: CGFloat = CGFloat(Float(i) * Float(frequencyWidth + frequencyMargin)) + margin
  283. linePath.move(to: CGPoint(x: originX, y: startY))
  284. // 终点
  285. linePath.addLine(to: CGPoint(x: originX, y: endY))
  286. let lineLayer = CAShapeLayer()
  287. lineLayer.lineWidth = frequencyWidth
  288. lineLayer.strokeColor = UIColor.hexColor(hexadecimal: "#999999").cgColor
  289. lineLayer.path = linePath.cgPath
  290. lineLayer.fillColor = UIColor.black.cgColor
  291. // 推荐的开始起点是虚线
  292. BFLog(1, message: "suggestRhythmStartTime is \(suggestRhythmStartTime)")
  293. if oneMarginTime * CGFloat(i) >= suggestRhythmStartTime && !isDrawLine {
  294. isDrawLine = true
  295. linePath.move(to: CGPoint(x: originX, y: -10))
  296. // 终点
  297. linePath.addLine(to: CGPoint(x: originX, y: 30))
  298. lineLayer.path = linePath.cgPath
  299. lineLayer.lineDashPhase = 0
  300. lineLayer.lineDashPattern = [3, 3]
  301. }
  302. if startLineX == 0 && oneMarginTime * CGFloat(i) >= stuckPointStartTime{
  303. startLineX = originX
  304. }
  305. lineLayerArray.append(lineLayer)
  306. rateView.layer.insertSublayer(lineLayer, at: 0)
  307. }
  308. }
  309. deinit {
  310. BFLog(message: "卡点裁剪-裁剪视图销毁")
  311. }
  312. //划动结速后处理
  313. func moveEnd() {
  314. //最后一个竖线VIEW
  315. let lastLine:UIView = scrollView.viewWithTag(100 + Int(videoDuration / timeRange) - 1) ?? UIView.init()
  316. //移动后的开始时间
  317. let startTime = videoDuration / lastLine.frame.maxX * scrollView.contentOffset.x
  318. // let startTime = videoDuration * (margin + scrollView.contentOffset.x) / scrollView.contentSize.width
  319. //选中的时长
  320. let selectDuration:CGFloat = CGFloat(stuckPointEndTime - stuckPointStartTime)
  321. BFLog(message: "拖拽结束 - 回调\(scrollView.contentOffset) \(scrollView.contentSize) 开始时间为:\(startTime) 结束时间为:\(startTime + selectDuration)")
  322. stuckPointStartTime = startTime
  323. stuckPointEndTime = stuckPointStartTime + selectDuration
  324. if(videoDidEndDragging != nil){
  325. videoDidEndDragging!(1,startTime,startTime + CGFloat(stuckPointEndTime - stuckPointStartTime),0)
  326. }
  327. resetDefaultsColor(clearData: false)
  328. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicPeriodSelect, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  329. }
  330. }
  331. // MARK: - scrollView滑动代理
  332. /// scrollView滑动代理
  333. extension PQStuckPointCuttingView: UIScrollViewDelegate {
  334. func scrollViewDidScroll(_: UIScrollView) {}
  335. func scrollViewWillBeginDragging(_ :UIScrollView){
  336. isUserDrag = true
  337. if(videoDidBeginDrag != nil){
  338. videoDidBeginDrag!()
  339. }
  340. }
  341. func scrollViewDidEndDecelerating(_: UIScrollView) {
  342. if !scrollView.isDragging, !scrollView.isDecelerating {
  343. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
  344. self?.moveEnd()
  345. }
  346. }
  347. }
  348. func scrollViewDidEndDragging(_:UIScrollView,willDecelerate decelerate:Bool){
  349. if !decelerate, !scrollView.isDragging, !scrollView.isDecelerating {
  350. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
  351. self?.moveEnd()
  352. }
  353. }
  354. }
  355. func scrollViewDidEndScrollingAnimation(_: UIScrollView) {
  356. BFLog(message: "scrollViewDidEndScrollingAnimation")
  357. }
  358. }