PQStuckPointEditerController.swift 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. //
  2. // PQStuckPointEditerController.swift
  3. // PQSpeed
  4. //
  5. // Created by ak on 2021/4/26.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. // 功能:卡点音乐编辑界面
  8. // 创建不同玩法的类型 (1:跳跃卡点,2:快慢速,3:仅配乐)
  9. public enum createStickersModel: Int {
  10. case createStickersModelPoint = 1 // 跳跃卡点
  11. case createStickersModelSpeed = 2 // 快慢速
  12. case createStickersModelOnlyMusic = 3 // 仅配乐
  13. }
  14. import Foundation
  15. import ObjectMapper
  16. import RealmSwift
  17. import UIKit
  18. class PQStuckPointEditerController: PQBaseViewController {
  19. // 是否导出视频成功
  20. var isExportVideosSuccess: Bool = false
  21. // 是否请求卡点数据成功
  22. var isStuckPointDataSuccess: Bool = false
  23. // 是否同步音乐成功
  24. var isSynchroMusicInfoSuccess: Bool = false
  25. /// 当前所有的filter
  26. var filters: Array = Array<ImageProcessingOperation>.init()
  27. // 选中所有素材的的总时长 再进入编辑界面时已经不包括图片的时长
  28. var selectedTotalDuration: Float64 = 0
  29. // 选择的总数
  30. var selectedDataCount: Int = 0
  31. // 选择的图片总数
  32. var selectedImageDataCount: Int = 0
  33. // 选中的素材数据
  34. var selectedPhotoData: [PQEditVisionTrackMaterialsModel]?
  35. // 选中的音乐数据
  36. var stuckPointMusicData: PQVoiceModel?
  37. // 保存所有段的所有贴纸,音频信息,用于播放器的渲染使用
  38. var projectModel: PQEditProjectModel = PQEditProjectModel()
  39. // 从草稿箱进入的项目数据
  40. var draftProjectModel: PQEditProjectModel?
  41. var mStickers: [PQEditVisionTrackMaterialsModel]?
  42. // 播放器的开始和结束时间,1,刚进界面使用推荐的开始结束时间,2,用户修改起结点时修改
  43. var playeTimeRange: CMTimeRange = CMTimeRange()
  44. // add by ak 是否是再创作模式
  45. var isReCreate: Bool = false
  46. public var reCreateVideoData: PQReCreateModel? // 再创作数据
  47. // 最后一个选择的模式 BTN 用于还原选中状态
  48. var lastEditModelBtn: UIButton?
  49. // add by ak 最大、最小速度 有固定值和自定义,当快慢速下两个值都有效,当跳跃卡点只有maxSpeed有效
  50. var maxSpeed: Float = 1
  51. var minSpeed: Float = 1
  52. // 快慢速最后一次选择的速度位置
  53. var lastSpeedSelectIndex: Int = 0
  54. // 跳跃卡点最后一次选择的速度位置
  55. var lastJumpSpeedSelectIndex: Int = 0
  56. // 循环次数设置最后一次选择的位置
  57. var lastCyclesSelectIndex: Int = -1
  58. // 当前选择的玩法模式
  59. var currentCreateStickersModel: createStickersModel = .createStickersModelSpeed
  60. // 最终使用的卡点数据
  61. var finallyStuckPoints: Array = Array<Float>.init()
  62. var finallyStuckPointsInt64: Array = Array<Int64>.init()
  63. // 最终使用的音频时长
  64. var finallyUserAudioTime: Float = 0.0
  65. // 注意推荐时间位置和后面最近的卡点时间与0.3的关系
  66. // 保存丢卡点处理后的卡点信息推荐开始到最后倒数第二个
  67. // 经过档位处理后的卡点信息
  68. var stuckPointsTemp: Array = Array<Float>.init()
  69. var stuckPointsTempInt64: Array = Array<Int64>.init()
  70. // 下一步
  71. lazy var nextBtn: UIButton = {
  72. let nextBtn = UIButton(type: .custom)
  73. nextBtn.frame = CGRect(x: cScreenWidth - 16 - cDefaultMargin * 6, y: cDevice_iPhoneStatusBarHei + (cDevice_iPhoneNavBarHei - cDefaultMargin * 3) / 2, width: cDefaultMargin * 6, height: cDefaultMargin * 3)
  74. nextBtn.setTitle("合成", for: .normal)
  75. nextBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
  76. nextBtn.addTarget(self, action: #selector(nextBtnClick(sender:)), for: .touchUpInside)
  77. nextBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  78. nextBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#FFFFFF"), for: .normal)
  79. nextBtn.uxy_acceptEventInterval = 0.5
  80. nextBtn.addCorner(corner: 3)
  81. return nextBtn
  82. }()
  83. // 播放器显示 view
  84. lazy var playerView: PQGPUImagePlayerView = {
  85. let playerHeight = cScreenWidth
  86. let playerView = PQGPUImagePlayerView(frame: CGRect(x: 0, y: navHeadImageView?.frame.maxY ?? 0, width: playerHeight, height: playerHeight))
  87. playerView.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  88. playerView.isShowLine = false
  89. playerView.showGaussianBlur = true
  90. playerView.renderViewOnClickHandle = { [weak self] in
  91. self?.musicEditBGView.pausePlayer()
  92. }
  93. playerView.playerEmptyView.isHidden = true
  94. return playerView
  95. }()
  96. /// 节奏选择视图
  97. lazy var sustomSwitchView: PQCustomSwitchView = {
  98. let sustomSwitchView = PQCustomSwitchView(frame: CGRect(x: 16, y: 0, width: 180, height: 30), titles: ["慢节奏", "适中", "快节奏"], defaultIndex: stuckPointMusicData?.speed ?? 2)
  99. sustomSwitchView.switchChangeHandle = { [weak self] sender in
  100. // 改变速率,.只有快慢速且非只有图片素材时自动+1处理
  101. self?.stuckPointMusicData?.speed = sender.tag
  102. self?.musicEditBGView.pausePlayer()
  103. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.bgmInfo?.rhythmMusicSpeed = sender.tag
  104. // 播放前先暂停
  105. // self?.playerView.stop()
  106. // 开始播放
  107. self?.settingPlayerView()
  108. // 下面都是统计
  109. if self?.currentCreateStickersModel == .createStickersModelPoint {
  110. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectMusicVideoRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  111. } else if self?.currentCreateStickersModel == .createStickersModelSpeed {
  112. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectSpeedRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  113. } else if self?.currentCreateStickersModel == .createStickersModelOnlyMusic {
  114. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectMusicVideoRepeatRhythm, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "点击上报:选择节奏")
  115. }
  116. }
  117. return sustomSwitchView
  118. }()
  119. /// 裁剪视图
  120. lazy var stuckPointCuttingView: PQStuckPointCuttingView = {
  121. let stuckPointCuttingView = PQStuckPointCuttingView(frame: CGRect(x: 0, y: optionlineView.frame.minY - 85 - 28, width: view.frame.width, height: 80), duration: CGFloat(Float(stuckPointMusicData?.duration ?? "0") ?? 0), startTime: CGFloat(stuckPointMusicData?.startTime ?? 0), endTime: CGFloat(stuckPointMusicData?.endTime ?? 0))
  122. /// 裁剪进度回调
  123. stuckPointCuttingView.videoDidBeginDrag = { [weak self] in
  124. BFLog(message: "开始划动")
  125. self?.playerView.pause()
  126. }
  127. /// 播放进度回调
  128. stuckPointCuttingView.videoProgressDidChanged = { [weak self] progress in
  129. BFLog(message: "进度更新返回--progress = \(progress) \(String(describing: self?.playerView.mPlayeTimeRange))")
  130. }
  131. /// 拖缀结束的回调 type - 1-拖动左边裁剪结束 2--拖动右边裁剪结束 3-进度条拖动结束 4-滑动结束
  132. stuckPointCuttingView.videoDidEndDragging = { [weak self] type, startTime, endTime, progress in
  133. BFLog(1, message: "拖拽结束返回--type = \(type),startTime = \(startTime),endTime = \(endTime),progress = \(progress)")
  134. self?.playerView.pause()
  135. self?.musicEditBGView.pausePlayer()
  136. // 修改最新值
  137. self?.stuckPointMusicData?.startTime = Float64(startTime)
  138. self?.stuckPointMusicData?.endTime = Float64(endTime)
  139. // 红的指针完成
  140. if type == 3 {
  141. if CMTimeGetSeconds(self?.playerView.mPlayeTimeRange?.end ?? .zero) == 0 {
  142. BFLog(message: "mPlayeTimeRange is error")
  143. return
  144. }
  145. let newBeginSconds = (Double(startTime) + (Double(endTime) - Double(startTime)) * Double(progress)) * 600
  146. BFLog(message: " newBeginSconds is \(newBeginSconds)")
  147. let seekTimeRange: CMTimeRange = CMTimeRange(start: CMTime(value: CMTimeValue(Int64(newBeginSconds)), timescale: 600), end:
  148. CMTime(value: CMTimeValue(Int64(endTime * 600)), timescale: 600))
  149. BFLog(message: "修改的开始 \(CMTimeGetSeconds(seekTimeRange.start)) 结束 \(CMTimeGetSeconds(seekTimeRange.end))")
  150. // 重新设置有效缓存
  151. self?.playerView.configCache(beginTime: CMTimeGetSeconds(seekTimeRange.start))
  152. self?.playerView.play(pauseFirstFrame: false, playeTimeRange: seekTimeRange)
  153. } else {
  154. // 更改素材开始时间及结束时间
  155. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.out = Float64(endTime)
  156. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.model_in = Float64(startTime)
  157. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.timelineIn = Float64(startTime)
  158. self?.projectModel.sData?.getBGMSession()?.sectionTimeline?.audioTrack?.audioTrackMaterials.first?.timelineOut = Float64(endTime)
  159. BFLog(message: "调整后总时长: \(endTime - startTime) startTime:\(startTime) endTime:\(endTime)")
  160. // 初始化音频的开始和结束时间
  161. self?.playeTimeRange = CMTimeRange(start: CMTimeMakeWithSeconds(Float64(startTime), preferredTimescale: BASE_FILTER_TIMESCALE), end: CMTimeMakeWithSeconds(Float64(endTime), preferredTimescale: BASE_FILTER_TIMESCALE))
  162. self?.dealParameter(model: self?.currentCreateStickersModel ?? .createStickersModelSpeed)
  163. if((self?.finallyStuckPoints.count ?? 0) < 1){
  164. BFLog(message: "finallyStuckPoints data is error!!!!")
  165. return
  166. }
  167. DispatchQueue.global().async { // 并行、异步
  168. let beginTime: TimeInterval = Date().timeIntervalSince1970
  169. self?.mStickers = self?.createStickers(sections: self?.projectModel.sData?.sections ?? List(), inputSize: CGSize(width: CGFloat(self?.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self?.projectModel.sData?.videoMetaData?.videoHeight ?? 0)), model: self?.currentCreateStickersModel ?? .createStickersModelSpeed)
  170. DispatchQueue.main.async { // 串行、异步
  171. self?.playerView.mStickers = self?.mStickers
  172. var endTime: TimeInterval = Date().timeIntervalSince1970
  173. BFLog(message: "endTime is endTimeendTime \(endTime = beginTime)")
  174. self?.playerView.play(pauseFirstFrame: false, playeTimeRange: self!.playeTimeRange)
  175. // 更新一下时间条的UI总时间 及数据
  176. self?.stuckPointCuttingView.videoDuration = CGFloat(self?.finallyUserAudioTime ?? 0)
  177. self?.stuckPointCuttingView.stuckPointStartTime = CGFloat(CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero))
  178. self?.stuckPointCuttingView.stuckPointEndTime = CGFloat(CMTimeGetSeconds(self?.playeTimeRange.end ?? .zero))
  179. self?.stuckPointCuttingView.tatalTimeLabel.text = "\(Float64(CMTimeGetSeconds(self?.playeTimeRange.end ?? .zero) - CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero)).formatDurationToHMS())"
  180. }
  181. }
  182. }
  183. }
  184. return stuckPointCuttingView
  185. }()
  186. /// 卡点模式标题
  187. lazy var pointEditRemindLab: UILabel = {
  188. let pointEditRemindLab = UILabel()
  189. pointEditRemindLab.backgroundColor = .clear
  190. pointEditRemindLab.textAlignment = .left
  191. pointEditRemindLab.font = UIFont.boldSystemFont(ofSize: 14)
  192. pointEditRemindLab.textColor = .black
  193. pointEditRemindLab.text = "卡点模式"
  194. return pointEditRemindLab
  195. }()
  196. /// 卡点模式标题
  197. lazy var speedTitleLab: UILabel = {
  198. let speedTitleLab = UILabel()
  199. speedTitleLab.backgroundColor = .clear
  200. speedTitleLab.textAlignment = .left
  201. speedTitleLab.font = UIFont.boldSystemFont(ofSize: 14)
  202. speedTitleLab.textColor = .black
  203. speedTitleLab.text = "节奏变化"
  204. return speedTitleLab
  205. }()
  206. /// 卡点模式下方操作区背景
  207. lazy var pointEditBGView: UIView = {
  208. let pointEditBGView = UIView()
  209. pointEditBGView.backgroundColor = .clear
  210. return pointEditBGView
  211. }()
  212. /// 下方音乐编辑操作区背景
  213. lazy var musicEditBGView: PQSelecteMusicView = {
  214. let musicEditBGView = PQSelecteMusicView()
  215. musicEditBGView.backgroundColor = .clear
  216. musicEditBGView.isUserInteractionEnabled = true
  217. musicEditBGView.isHidden = true
  218. musicEditBGView.musicSearchBtn.addTarget(self, action: #selector(musicSearchBtnClick(sender:)), for: .touchUpInside)
  219. musicEditBGView.didSelectItemHandle = { [weak self] _ in
  220. self?.playerView.pause()
  221. }
  222. musicEditBGView.btnClickHandle = { [weak self] _, bgmData in
  223. // 使用音乐
  224. self?.userstuckPointMusic(musicData: bgmData as? PQVoiceModel)
  225. }
  226. return musicEditBGView
  227. }()
  228. // 卡点编辑 btn
  229. lazy var pointEditerBtn: UIButton = {
  230. let pointEdterBtn = UIButton(type: .custom)
  231. pointEdterBtn.setImage(UIImage().BF_Image(named: "pointEditerBtn_n"), for: .normal)
  232. pointEdterBtn.setImage(UIImage().BF_Image(named: "pointEditerBtn_h"), for: .selected)
  233. pointEdterBtn.addTarget(self, action: #selector(pointEditerBtnClick(sender:)), for: .touchUpInside)
  234. pointEdterBtn.isSelected = true
  235. pointEdterBtn.adjustsImageWhenHighlighted = false
  236. return pointEdterBtn
  237. }()
  238. // 音乐编辑 btn
  239. lazy var musicEditerBtn: UIButton = {
  240. let musicEditerBtn = UIButton(type: .custom)
  241. musicEditerBtn.setImage(UIImage().BF_Image(named: "musicEditerBtn_n"), for: .normal)
  242. musicEditerBtn.setImage(UIImage().BF_Image(named: "musicEditerBtn_h"), for: .selected)
  243. musicEditerBtn.addTarget(self, action: #selector(musicEditerBtnClick(sender:)), for: .touchUpInside)
  244. musicEditerBtn.adjustsImageWhenHighlighted = false
  245. return musicEditerBtn
  246. }()
  247. // 快慢速卡点模式 btn
  248. lazy var speedStuckBtn: UIButton = {
  249. let speedStuckBtn = UIButton(type: .custom)
  250. speedStuckBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  251. speedStuckBtn.setBackgroundImage(UIImage().BF_Image(named: "speedstuck_n"), for: .normal)
  252. speedStuckBtn.setBackgroundImage(UIImage().BF_Image(named: "speedstuck_h"), for: .selected)
  253. speedStuckBtn.tag = 1
  254. speedStuckBtn.adjustsImageWhenHighlighted = false
  255. return speedStuckBtn
  256. }()
  257. //
  258. lazy var speedStuckBtnGif: UIImageView = {
  259. let speedStuckBtnGif = UIImageView()
  260. speedStuckBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: "speedstuck_h", ofType: ".gif")!))
  261. speedStuckBtnGif.isHidden = true
  262. return speedStuckBtnGif
  263. }()
  264. // 跳转卡点模式 btn
  265. lazy var jumpPointBtn: UIButton = {
  266. let jumpPointBtn = UIButton(type: .custom)
  267. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_n"), for: .normal)
  268. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_h"), for: .selected)
  269. jumpPointBtn.tag = 2
  270. jumpPointBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  271. jumpPointBtn.adjustsImageWhenHighlighted = false
  272. return jumpPointBtn
  273. }()
  274. lazy var jumpPointBtnGif: UIImageView = {
  275. let jumpPointBtnGif = UIImageView()
  276. jumpPointBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: "jumpPoint_n", ofType: ".gif")!))
  277. jumpPointBtnGif.isHidden = true
  278. return jumpPointBtnGif
  279. }()
  280. // 仅配乐模式 btn
  281. lazy var onlyMusicBtn: UIButton = {
  282. let onlyMusicBtn = UIButton(type: .custom)
  283. onlyMusicBtn.setImage(UIImage().BF_Image(named: "onlyMusic_n"), for: .normal)
  284. onlyMusicBtn.setImage(UIImage().BF_Image(named: "onlyMusic_h"), for: .selected)
  285. onlyMusicBtn.tag = 3
  286. onlyMusicBtn.addTarget(self, action: #selector(editModelClick1(sender:)), for: .touchUpInside)
  287. onlyMusicBtn.adjustsImageWhenHighlighted = false
  288. return onlyMusicBtn
  289. }()
  290. // 操作面板上的分割线
  291. lazy var optionlineView: UIView = {
  292. let optionlineView = UIView()
  293. optionlineView.backgroundColor = UIColor.hexColor(hexadecimal: "#EFEFEF")
  294. return optionlineView
  295. }()
  296. // 固定速度 UI
  297. lazy var speedSettingView: PQSpeedSettingView = {
  298. let speedSetView = PQSpeedSettingView()
  299. speedSetView.backgroundColor = .clear
  300. speedSetView.selectSpeedCallBack = { [weak self] maxSpeed, minSpeed, selectIndex, isSettingPlayer in
  301. BFLog(message: "固定maxSpeed is\(maxSpeed) minSpeed \(minSpeed)")
  302. self?.musicEditBGView.pausePlayer()
  303. if maxSpeed == -1.0 && minSpeed == -1.0 {
  304. self?.customSpeedSettingView.isHidden = false
  305. self?.customSpeedSettingView.viewType = self?.speedSettingView.viewType ?? 2
  306. } else {
  307. if maxSpeed != 0.0 {
  308. // 更新最后一次选择的位置恢复时使用
  309. if self?.speedSettingView.viewType == 1 {
  310. self?.lastSpeedSelectIndex = selectIndex
  311. } else if self?.speedSettingView.viewType == 2 {
  312. self?.lastJumpSpeedSelectIndex = selectIndex
  313. } else {
  314. self?.lastCyclesSelectIndex = selectIndex
  315. }
  316. self?.maxSpeed = maxSpeed
  317. self?.minSpeed = minSpeed
  318. } else {
  319. BFLog(message: "设置速度无效")
  320. }
  321. }
  322. if isSettingPlayer {
  323. self?.settingPlayerView()
  324. }
  325. }
  326. return speedSetView
  327. }()
  328. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  329. super.touchesBegan(touches, with: event)
  330. if touches.first?.view != self.customSpeedSettingView {
  331. if !customSpeedSettingView.isHidden {
  332. customSpeedSettingView.isHidden = true
  333. }
  334. }
  335. }
  336. // 自定义速度
  337. lazy var customSpeedSettingView: PQCustomSpeedSettingView = {
  338. let customSpeedSetView = PQCustomSpeedSettingView(frame: CGRect(x: 0, y: cScreenHeigth - 354, width: cScreenWidth, height: 354))
  339. customSpeedSetView.isHidden = true
  340. customSpeedSetView.selectSpeedCallBack = { [weak self, weak customSpeedSetView] maxSpeed, minSpeed, isJumpSpeedModel, isCancle in
  341. if !isCancle {
  342. self?.maxSpeed = maxSpeed
  343. self?.minSpeed = minSpeed
  344. BFLog(message: "自定义速度maxSpeed is\(maxSpeed) minSpeed \(minSpeed) \(isJumpSpeedModel)")
  345. self?.musicEditBGView.pausePlayer()
  346. // 自定定义的更新一下最后的选择位置
  347. if self?.speedSettingView.viewType == 1 {
  348. self?.lastSpeedSelectIndex = -1
  349. } else if self?.speedSettingView.viewType == 2 {
  350. self?.lastJumpSpeedSelectIndex = -1
  351. } else {
  352. self?.lastCyclesSelectIndex = Int(maxSpeed - 1)
  353. }
  354. self?.settingPlayerView()
  355. // 确认后 选中自定义
  356. self?.speedSettingView.selectCustom()
  357. } else {
  358. // 取消后恢复上一次选择的位置
  359. if self?.speedSettingView.viewType == 1 {
  360. self?.speedSettingView.setSelectItem(index: self?.lastSpeedSelectIndex ?? 0, isSettingPlayer: false)
  361. } else if self?.speedSettingView.viewType == 2 {
  362. self?.speedSettingView.setSelectItem(index: self?.lastJumpSpeedSelectIndex ?? 0, isSettingPlayer: false)
  363. } else {
  364. self?.speedSettingView.setSelectItem(index: self?.lastCyclesSelectIndex ?? 0, isSettingPlayer: false)
  365. }
  366. customSpeedSetView?.isHidden = true
  367. }
  368. }
  369. return customSpeedSetView
  370. }()
  371. /// 音乐标题
  372. lazy var musicNameView: UIView = {
  373. let musicNameView = UIView()
  374. musicNameView.addSubview(musicNameLab)
  375. let nameWidth: CGFloat = musicNameLab.frame.width + (25 + cDefaultMargin * 3)
  376. musicNameView.frame = CGRect(x: (view.frame.width - nameWidth) / 2, y: cDevice_iPhoneStatusBarHei + (cDevice_iPhoneNavBarHei - cDefaultMargin * 3) / 2, width: nameWidth, height: cDefaultMargin * 3)
  377. // musicNameView.backgroundColor = UIColor.hexColor(hexadecimal: "#333333")
  378. musicNameView.addCorner(corner: musicNameView.frame.height / 2)
  379. let musicImageView = UIImageView()
  380. musicImageView.tintColor = PQBFConfig.shared.styleTitleColor
  381. musicImageView.image = UIImage().BF_Image(named: "stuckPoint_reCreate_music").withRenderingMode(.alwaysTemplate)
  382. musicImageView.frame = CGRect(x: musicNameView.frame.height / 2 - 5, y: (musicNameView.frame.height - 22) / 2, width: 22, height: 22)
  383. musicNameView.addSubview(musicImageView)
  384. musicNameLab.frame.origin.x = musicImageView.frame.maxX + 5
  385. return musicNameView
  386. }()
  387. /// 音乐歌曲名称
  388. lazy var musicNameLab: LMJHorizontalScrollText = {
  389. let nameWidth: CGFloat = sizeWithText(text: "\(stuckPointMusicData?.musicName ?? "")", font: UIFont.systemFont(ofSize: 13), size: CGSize(width: view.frame.width - ((cDefaultMargin * 6 + 16 * 2) * 2) - (25 + cDefaultMargin * 3), height: cDefaultMargin * 3)).width
  390. let musicNameLab = LMJHorizontalScrollText(frame: CGRect(x: 0, y: 0, width: nameWidth < cDefaultMargin * 4 ? cDefaultMargin * 4 : nameWidth, height: cDefaultMargin * 3))
  391. musicNameLab.textColor = PQBFConfig.shared.styleTitleColor
  392. musicNameLab.textFont = UIFont.systemFont(ofSize: 13)
  393. musicNameLab.speed = 0.03
  394. musicNameLab.moveDirection = LMJTextScrollMoveLeft
  395. musicNameLab.moveMode = LMJTextScrollContinuous
  396. if nameWidth < cDefaultMargin * 4 {
  397. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  398. } else {
  399. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  400. }
  401. return musicNameLab
  402. }()
  403. /// 同步进度显示
  404. lazy var synchroMarskView: PQStuckPointLoadingView = {
  405. var synchroMarskView = PQStuckPointLoadingView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
  406. synchroMarskView.cancelHandle = { [weak self] _ in
  407. self?.navigationController?.popViewController(animated: true)
  408. }
  409. return synchroMarskView
  410. }()
  411. override func viewWillAppear(_ animated: Bool) {
  412. super.viewDidAppear(animated)
  413. lineView?.isHidden = true
  414. UIApplication.shared.isIdleTimerDisabled = true
  415. musicNameLab.move()
  416. PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  417. PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  418. }
  419. @objc func willEnterForeground() {
  420. BFLog(message: "进入到前台")
  421. if(self.navigationController?.topViewController == self){
  422. settingPlayerView()
  423. }
  424. }
  425. @objc func enterBackground() {
  426. BFLog(message: "进入到后台")
  427. // 取消导出
  428. if(self.navigationController?.topViewController == self){
  429. playerView.pause()
  430. }
  431. }
  432. override func backBtnClick() {
  433. super.backBtnClick()
  434. // playerView.pause()
  435. // 点击上报:返回按钮
  436. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_back, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(点击上报:返回按钮)")
  437. }
  438. // 使用选择音乐 调用情况:1,操作面板直接选择 ,2 搜索界面点击使用
  439. func userstuckPointMusic(musicData: PQVoiceModel?) {
  440. // 1,音乐面板点击了使用
  441. stuckPointMusicData = musicData
  442. // 2,同步最新音乐数据
  443. synchroMusicInfoData()
  444. // 3,更新音乐标题UI
  445. let nameWidth: CGFloat = sizeWithText(text: "\(stuckPointMusicData?.musicName ?? "")", font: UIFont.systemFont(ofSize: 13), size: CGSize(width: (view.frame.width) - ((cDefaultMargin * 6 + 16 * 2) * 2) - (25 + cDefaultMargin * 3), height: cDefaultMargin * 3)).width
  446. if nameWidth < cDefaultMargin * 4 {
  447. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  448. } else {
  449. musicNameLab.text = " \(stuckPointMusicData?.musicName ?? "") "
  450. }
  451. // 更新一下节奏的 UI
  452. sustomSwitchView.selectOneBtn(Index: (stuckPointMusicData?.speed ?? 2))
  453. }
  454. // 点击搜索音乐
  455. @objc func musicSearchBtnClick(sender _: UIButton) {
  456. let searchVC = PQEditMusicSearchController()
  457. searchVC.btnClickHandle = { [weak self] _, bgmData in
  458. // 使用音乐
  459. BFLog(message: "搜索音乐点击了使用")
  460. self?.musicEditBGView.insertSearchMusic(model: bgmData as! PQVoiceModel)
  461. self?.userstuckPointMusic(musicData: bgmData as? PQVoiceModel)
  462. }
  463. let navigationController: UINavigationController = UINavigationController(rootViewController: searchVC)
  464. navigationController.modalPresentationStyle = .fullScreen
  465. present(navigationController, animated: true, completion: nil)
  466. }
  467. // 卡点编辑
  468. @objc func pointEditerBtnClick(sender: UIButton) {
  469. if sender.isSelected { return }
  470. sender.isSelected = !sender.isSelected
  471. musicEditerBtn.isSelected = false
  472. pointEditBGView.isHidden = false
  473. musicEditBGView.isHidden = true
  474. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_videoTab, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  475. }
  476. // 音乐编辑
  477. @objc func musicEditerBtnClick(sender: UIButton) {
  478. if sender.isSelected { return }
  479. sender.isSelected = !sender.isSelected
  480. pointEditerBtn.isSelected = false
  481. pointEditBGView.isHidden = true
  482. musicEditBGView.showData()
  483. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicTab, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  484. }
  485. @objc func editModelClick1(sender: UIButton) {
  486. editModelClick(sender: sender)
  487. }
  488. // 三种模式修改
  489. @objc func editModelClick(sender: UIButton, reportLog: Bool = true) {
  490. // if sender.isSelected {
  491. // BFLog(message: "已经是选中状态")
  492. // return “”
  493. // }
  494. self.musicEditBGView.pausePlayer()
  495. if sender == jumpPointBtn && selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount {
  496. cShowHUB(superView: view, msg: "素材时长需要大于6秒才\n可选择“跳跃卡点”模式")
  497. return
  498. }
  499. lastEditModelBtn?.isSelected = false
  500. sender.isSelected = !sender.isSelected
  501. lastEditModelBtn = sender
  502. BFLog(message: "sender tag is \(sender.tag)")
  503. // 1 ui 调整
  504. if sender.tag == 1 || sender.tag == 2 {
  505. speedSettingView.viewType = sender.tag
  506. customSpeedSettingView.viewType = speedSettingView.viewType
  507. speedSettingView.snp.remakeConstraints { make in
  508. make.left.equalToSuperview().offset(16)
  509. make.right.equalToSuperview()
  510. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  511. make.height.equalTo(sender.tag == 1 ? 44 : 30)
  512. }
  513. speedSettingView.isHidden = false
  514. speedTitleLab.isHidden = false
  515. sustomSwitchView.isHidden = false
  516. } else {
  517. speedTitleLab.isHidden = true
  518. speedSettingView.isHidden = true
  519. sustomSwitchView.isHidden = true
  520. }
  521. // 2素材全是图片的时候三个模式都显示循环设置 UI
  522. if selectedDataCount == selectedImageDataCount {
  523. speedSettingView.viewType = 3
  524. customSpeedSettingView.viewType = speedSettingView.viewType
  525. speedSettingView.snp.remakeConstraints { make in
  526. make.left.equalToSuperview().offset(16)
  527. make.right.equalToSuperview()
  528. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  529. make.height.equalTo(30)
  530. }
  531. speedSettingView.isHidden = false
  532. speedTitleLab.isHidden = false
  533. sustomSwitchView.isHidden = false
  534. if lastCyclesSelectIndex != -1 {
  535. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false)
  536. }
  537. } else {
  538. if sender.tag == 1 { // 快慢速
  539. speedSettingView.setSelectItem(index: lastSpeedSelectIndex, isSettingPlayer: false, setDisable: (selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount) ? true : false)
  540. } else if sender.tag == 2 { // 跳跃卡点
  541. speedSettingView.setSelectItem(index: lastJumpSpeedSelectIndex, isSettingPlayer: false)
  542. } else if sender.tag == 3 { // 仅音乐
  543. // customSpeedSettingView.isJumpSpeedModel = false
  544. }
  545. }
  546. // 3 设置 btn 不同显示状态
  547. var speedStuckBtnGifName = ""
  548. var jumpPointBtnGifName = ""
  549. if sender.tag == 1 { // 快慢速
  550. speedStuckBtnGifName = "speedstuck_h"
  551. jumpPointBtnGifName = "jumpPoint_n"
  552. currentCreateStickersModel = .createStickersModelSpeed
  553. if reportLog {
  554. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternSpeed, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  555. }
  556. } else if sender.tag == 2 { // 跳跃卡点
  557. speedStuckBtnGifName = "speedstuck_n"
  558. jumpPointBtnGifName = "jumpPoint_h"
  559. currentCreateStickersModel = .createStickersModelPoint
  560. if reportLog {
  561. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternMusicVideo, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  562. }
  563. } else if sender.tag == 3 { // 仅音乐
  564. speedStuckBtnGifName = "speedstuck_n"
  565. jumpPointBtnGifName = "jumpPoint_n"
  566. currentCreateStickersModel = .createStickersModelOnlyMusic
  567. if reportLog {
  568. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectPatternBgm, pageSource: .sp_shanyinApp_main, extParams: nil, remindmsg: "")
  569. }
  570. }
  571. speedStuckBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: speedStuckBtnGifName, ofType: ".gif")!))
  572. jumpPointBtnGif.kf.setImage(with: URL(fileURLWithPath: Bundle().BF_mainbundle().path(forResource: jumpPointBtnGifName, ofType: ".gif")!))
  573. speedStuckBtnGif.isHidden = false
  574. jumpPointBtnGif.isHidden = false
  575. settingPlayerView()
  576. }
  577. override func viewWillDisappear(_ animated: Bool) {
  578. super.viewWillDisappear(animated)
  579. UIApplication.shared.isIdleTimerDisabled = false
  580. musicNameLab.stop()
  581. playerView.pause()
  582. musicEditBGView.pausePlayer()
  583. }
  584. override func viewDidLoad() {
  585. super.viewDidLoad()
  586. leftButton(image: "icon_detail_back", tintColor: PQBFConfig.shared.styleTitleColor)
  587. navHeadImageView?.addSubview(nextBtn)
  588. navHeadImageView?.addSubview(musicNameView)
  589. // 添加子视图
  590. addSubViews()
  591. // 导出相册视频
  592. exportPhotoData()
  593. // 同步音乐数据
  594. synchroMusicInfoData()
  595. // 插入选择的音乐信息
  596. musicEditBGView.firstInsertVoiceModel = stuckPointMusicData!
  597. // 曝光上报:预览页面曝光上报
  598. PQEventTrackViewModel.baseReportUpload(businessType: .bt_windowView, objectType: .ot_view_previewSyncedUp, pageSource: .sp_stuck_previewSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(曝光上报:预览页面曝光上报)")
  599. }
  600. /// 添加子视图
  601. /// - Returns: <#description#>
  602. func addSubViews() {
  603. if (stuckPointMusicData?.rhythmSdata.count ?? 0) <= 0 {
  604. return
  605. }
  606. view.addSubview(playerView)
  607. view.addSubview(pointEditBGView)
  608. view.addSubview(musicEditBGView)
  609. view.addSubview(optionlineView)
  610. view.addSubview(pointEditerBtn)
  611. view.addSubview(musicEditerBtn)
  612. view.addSubview(customSpeedSettingView)
  613. // 卡点
  614. pointEditBGView.addSubview(pointEditRemindLab)
  615. pointEditBGView.addSubview(speedTitleLab)
  616. pointEditBGView.addSubview(speedStuckBtn)
  617. speedStuckBtn.addSubview(speedStuckBtnGif)
  618. pointEditBGView.addSubview(jumpPointBtn)
  619. jumpPointBtn.addSubview(jumpPointBtnGif)
  620. pointEditBGView.addSubview(onlyMusicBtn)
  621. pointEditBGView.addSubview(speedSettingView)
  622. pointEditBGView.addSubview(sustomSwitchView)
  623. // 音乐
  624. musicEditBGView.addSubview(stuckPointCuttingView)
  625. pointEditerBtn.snp.makeConstraints { make in
  626. make.left.equalToSuperview().offset(100)
  627. make.bottom.equalToSuperview().offset(-(14 + cAKSafeAreaHeight))
  628. make.height.equalTo(24)
  629. make.width.equalTo(24)
  630. }
  631. musicEditerBtn.snp.makeConstraints { make in
  632. make.right.equalToSuperview().offset(-100)
  633. make.top.equalTo(pointEditerBtn.snp_top)
  634. make.height.equalTo(24)
  635. make.width.equalTo(24)
  636. }
  637. pointEditBGView.snp.makeConstraints { make in
  638. make.left.right.equalTo(view)
  639. make.bottom.equalTo(pointEditerBtn.snp_top).offset(-7)
  640. make.height.equalTo(290)
  641. }
  642. musicEditBGView.snp.makeConstraints { make in
  643. make.left.right.equalTo(view)
  644. make.bottom.equalTo(pointEditerBtn.snp_top).offset(-7)
  645. make.height.equalTo(290)
  646. }
  647. stuckPointCuttingView.snp.makeConstraints { make in
  648. make.left.right.equalTo(view)
  649. make.bottom.equalTo(pointEditerBtn.snp_top).offset(-12)
  650. make.height.equalTo(290)
  651. }
  652. optionlineView.snp.makeConstraints { make in
  653. make.left.right.equalToSuperview()
  654. make.bottom.equalTo(pointEditBGView.snp_bottom).offset(-1)
  655. make.height.equalTo(1)
  656. }
  657. stuckPointCuttingView.snp.makeConstraints { make in
  658. make.left.right.equalToSuperview()
  659. make.bottom.equalTo(musicEditBGView.snp_bottom).offset(-1)
  660. make.height.equalTo(85)
  661. }
  662. pointEditRemindLab.snp.makeConstraints { make in
  663. make.left.equalToSuperview().offset(16)
  664. make.top.equalToSuperview().offset(16)
  665. make.height.equalTo(20)
  666. make.width.equalTo(80)
  667. }
  668. speedStuckBtn.snp.makeConstraints { make in
  669. make.left.equalToSuperview().offset(16)
  670. make.top.equalTo(pointEditRemindLab.snp_bottom).offset(8)
  671. make.height.equalTo(80)
  672. make.width.equalTo(80)
  673. }
  674. speedStuckBtnGif.snp.makeConstraints { make in
  675. make.height.width.equalTo(46)
  676. make.top.equalToSuperview().offset(8)
  677. make.centerX.equalToSuperview()
  678. }
  679. jumpPointBtn.snp.makeConstraints { make in
  680. make.left.equalTo(speedStuckBtn.snp_right).offset(10)
  681. make.top.equalTo(speedStuckBtn.snp_top)
  682. make.height.equalTo(80)
  683. make.width.equalTo(80)
  684. }
  685. jumpPointBtnGif.snp.makeConstraints { make in
  686. make.height.width.equalTo(46)
  687. make.top.equalToSuperview().offset(8)
  688. make.centerX.equalToSuperview()
  689. }
  690. onlyMusicBtn.snp.makeConstraints { make in
  691. make.left.equalTo(jumpPointBtn.snp_right).offset(10)
  692. make.top.equalTo(speedStuckBtn.snp_top)
  693. make.height.equalTo(80)
  694. make.width.equalTo(64)
  695. }
  696. speedSettingView.snp.makeConstraints { make in
  697. make.left.equalToSuperview().offset(16)
  698. make.right.equalToSuperview()
  699. make.top.equalTo(onlyMusicBtn.snp_bottom).offset(10)
  700. make.height.equalTo(44)
  701. }
  702. speedTitleLab.snp.makeConstraints { make in
  703. make.left.equalToSuperview().offset(16)
  704. make.top.equalToSuperview().offset(190)
  705. make.height.equalTo(20)
  706. make.width.equalTo(80)
  707. }
  708. sustomSwitchView.snp.makeConstraints { make in
  709. make.left.equalToSuperview().offset(16)
  710. make.top.equalTo(speedTitleLab.snp_bottom).offset(8)
  711. make.height.equalTo(30)
  712. make.width.equalTo(180)
  713. }
  714. }
  715. @objc func nextBtnClick(sender _: UIButton) {
  716. BFLog(message: "去发布")
  717. playerView.pause()
  718. let videoExporter = PQStuckPointPublicController()
  719. videoExporter.rhythmMode = currentCreateStickersModel
  720. videoExporter.syncedUpVideoSpeedMin = minSpeed
  721. videoExporter.syncedUpVideoSpeedMax = maxSpeed
  722. videoExporter.isReCreate = isReCreate
  723. videoExporter.selectedTotalDuration = selectedTotalDuration
  724. videoExporter.selectedDataCount = selectedDataCount
  725. videoExporter.selectedImageDataCount = selectedImageDataCount
  726. videoExporter.finallyUserAudioTime = finallyUserAudioTime
  727. videoExporter.clipAudioRange = getClipAudioRange()
  728. videoExporter.playeTimeRange = playeTimeRange
  729. // 使用深 copy
  730. let json = projectModel.toJSONString(prettyPrint: false)
  731. if json == nil {
  732. BFLog(message: "数据转换有问题 跳转")
  733. return
  734. }
  735. let tempModel: PQEditProjectModel? = Mapper<PQEditProjectModel>().map(JSONString: json!)
  736. videoExporter.mStickers = mStickers
  737. videoExporter.audioMixModel = stuckPointMusicData
  738. videoExporter.editProjectModel = tempModel
  739. navigationController?.pushViewController(videoExporter, animated: true)
  740. // 点击上报:去合成
  741. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_commit, pageSource: .sp_stuck_previewSyncedUp, extParams: ["musicName": stuckPointMusicData?.musicName ?? "", "musicId": stuckPointMusicData?.musicId ?? "", "rhythmNumber": stuckPointMusicData?.speed ?? 2, "duration": ((stuckPointMusicData?.endTime ?? 0) - (stuckPointMusicData?.startTime ?? 0)) * 1000], remindmsg: "点击上报:去合成")
  742. }
  743. // MARK: - 播放器相关操作
  744. /// seek 播放器
  745. /// - Parameter playeTimeRange: 开始和结束时间
  746. func seekPlayer(playeTimeRange: CMTimeRange) {
  747. playerView.setEnableSeek(isSeek: true)
  748. playerView.play(pauseFirstFrame: false, playeTimeRange: playeTimeRange)
  749. }
  750. /// 通过传入的 selectedPhotoData 、 stuckPointMusicData 创建 projectModel 模型 后面都使用 projectModel 参数
  751. func createPorjectData() {
  752. // 1,添加选择的视觉素材
  753. if projectModel.sData?.sections.count == 0 {
  754. let section: PQEditSectionModel = PQEditSectionModel()
  755. selectedPhotoData?.forEach { model in
  756. let json = model.toJSONString(prettyPrint: false)
  757. if json == nil {
  758. BFLog(message: "数据转换有问题 跳转")
  759. return
  760. }
  761. let tempModel: PQEditVisionTrackMaterialsModel = Mapper<PQEditVisionTrackMaterialsModel>().map(JSONString: json!)!
  762. section.sectionTimeline?.visionTrack?.visionTrackMaterials.append(tempModel)
  763. }
  764. projectModel.sData?.sections.append(section)
  765. }
  766. // 2,添加背景音乐
  767. projectModel.sData?.addBGM(audioMix: stuckPointMusicData!)
  768. }
  769. // 计算拼接音乐的开始和结束点
  770. func getClipAudioRange() -> CMTimeRange {
  771. // 设置音乐的拼接范围,开始:推荐的卡点 结束:点到的倒数第二位
  772. let lastSecondPoint = Float((stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 2])) / Float(BASE_FILTER_TIMESCALE)
  773. let clipAudioRange =
  774. CMTimeRange(start: CMTime(value: CMTimeValue(Float(stuckPointMusicData?.startTime ?? 0) * Float(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE), end: CMTime(value: CMTimeValue((Float(lastSecondPoint)) * Float(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE))
  775. return clipAudioRange
  776. }
  777. // 设置播放器
  778. func settingPlayerView() {
  779. stuckPointCuttingView.resetDefaultsColor()
  780. synchroMarskView.removeFromSuperview()
  781. if synchroMarskView.superview == nil {
  782. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  783. synchroMarskView.show()
  784. }
  785. // 1,设置播放器的显示区域 和画布大小
  786. // - 按第一个素材尺寸自适应
  787. playerView.pause()
  788. let playerShowHeight = pointEditBGView.frame.minY - (navHeadImageView?.frame.maxY ?? 0)
  789. var showRect: CGRect = PQPlayerViewModel.getShowCanvasRect(editProjectModel: projectModel, showType: 1, playerViewHeight: playerShowHeight)
  790. if showRect.size.width == showRect.size.height {
  791. if cScreenWidth > playerShowHeight {
  792. showRect.origin.x = (cScreenWidth - playerShowHeight) / 2
  793. showRect.size.width = playerShowHeight
  794. showRect.size.height = playerShowHeight
  795. } else {
  796. showRect.origin.x = 0
  797. showRect.size.width = cScreenWidth
  798. showRect.size.height = cScreenWidth
  799. }
  800. }
  801. if showRect.size.width != 0, showRect.size.height != 0 {
  802. if(Int(showRect.height) % 2 != 0){
  803. showRect.size.height = showRect.size.height + 1.0
  804. }
  805. if(Int(showRect.width) % 2 != 0){
  806. showRect.size.width = showRect.size.width + 1.0
  807. }
  808. }
  809. showRect.origin.y = (playerShowHeight - showRect.size.height) / 2.0 + (navHeadImageView?.frame.maxY ?? 0)
  810. playerView.resetCanvasFrame(frame: showRect)
  811. var firstModel: PQEditVisionTrackMaterialsModel?
  812. for part in projectModel.sData!.sections {
  813. if part.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().count ?? 0 > 0 {
  814. firstModel = part.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().first
  815. break
  816. }
  817. }
  818. var videoSize: CGSize = CGSize(width: Int(firstModel?.width ?? 0), height: Int(firstModel?.height ?? 0))
  819. var minSlider = min(videoSize.width, videoSize.height)
  820. var maxSlider = max(videoSize.width, videoSize.height)
  821. let ration = 1080 / minSlider
  822. minSlider = minSlider * ration
  823. maxSlider = maxSlider * ration
  824. if videoSize.width > videoSize.height { // 宽屏
  825. videoSize = CGSize(width: maxSlider, height: minSlider)
  826. } else {
  827. videoSize = CGSize(width: minSlider, height: maxSlider)
  828. }
  829. let maxValue = max(videoSize.width, videoSize.height)
  830. if maxValue > 1920 {
  831. let maxRation = 1920 / maxValue
  832. videoSize = CGSize(width: videoSize.width * CGFloat(maxRation), height: videoSize.height * CGFloat(maxRation))
  833. BFLog(message: "最长边已经超过 1920 要等比缩小 缩放后\(videoSize)")
  834. }
  835. if (Int(videoSize.width) % 2) != 0 {
  836. videoSize.width = videoSize.width - 1
  837. }
  838. if (Int(videoSize.height) % 2) != 0 {
  839. videoSize.height = videoSize.height - 1
  840. }
  841. projectModel.sData?.videoMetaData?.videoWidth = Int(videoSize.width)
  842. projectModel.sData?.videoMetaData?.videoHeight = Int(videoSize.height)
  843. let beginTime: TimeInterval = Date().timeIntervalSince1970
  844. dealParameter(model: currentCreateStickersModel)
  845. // 更新裁剪时间条的的ui数据
  846. stuckPointCuttingView.videoDuration = max(CGFloat(finallyUserAudioTime), CGFloat(finallyStuckPoints.last!))
  847. stuckPointCuttingView.updateEndTime(startTime: CGFloat(CMTimeGetSeconds(playeTimeRange.start)), endTime: CGFloat(CMTimeGetSeconds(playeTimeRange.end)))
  848. // 2,创建滤镜
  849. DispatchQueue.global().async {
  850. self.mStickers = self.createStickers(sections: self.projectModel.sData?.sections ?? List(), inputSize: CGSize(width: CGFloat(self.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self.projectModel.sData?.videoMetaData?.videoHeight ?? 0)), model: self.currentCreateStickersModel)
  851. DispatchQueue.main.async { // 串行、异步
  852. self.playerView.mStickers = self.mStickers
  853. let end: TimeInterval = Date().timeIntervalSince1970
  854. BFLog(message: "createStickers tiskskskskme \(end - beginTime)")
  855. // 3,设置音频
  856. let audioPath = self.stuckPointMusicData?.localPath ?? ""
  857. BFLog(message: "初始化音频播放器的音频地址为:\(audioPath)")
  858. self.playerView.stop()
  859. // 这里的测试这个音乐播放有问题
  860. // self.playerView.updateAsset(URL(fileURLWithPath: "63930549652d74e477141e3b79c8d29a9ef8af81625053214516.mp3", relativeTo:Bundle.main.resourceURL!), videoComposition: nil, audioMixModel: nil)
  861. self.playerView.updateAsset(URL(fileURLWithPath: documensDirectory + audioPath), videoComposition: nil, audioMixModel: nil, originMusicDuration: self.finallyUserAudioTime, clipAudioRange: self.getClipAudioRange())
  862. let end2: TimeInterval = Date().timeIntervalSince1970
  863. BFLog(message: "updateAsset tiskskskskme \(end2 - end)")
  864. // 4, 设置播放器的输出画布大小
  865. self.playerView.movie?.mShowVidoSize = CGSize(width: CGFloat(self.projectModel.sData?.videoMetaData?.videoWidth ?? 0), height: CGFloat(self.projectModel.sData?.videoMetaData?.videoHeight ?? 0))
  866. // 传给movie 音频的原始卡点
  867. let fir = Int64(self.stuckPointsTemp.first ?? 0)
  868. let endd = Int64(self.stuckPointsTemp.last ?? 0)
  869. self.playerView.movie?.orginStuckRange = CMTimeRange(start: CMTime(value: Int64(fir) * 40, timescale: 40), end: CMTime(value: Int64(endd) * 40, timescale: 40))
  870. // 5,开始播放
  871. self.playerView.isLoop = false
  872. self.playerView.showProgressLab = true
  873. // 初始化音频的开始和结束时间
  874. BFLog(message: "播放的器 开始\(String(describing: CMTimeGetSeconds(self.playeTimeRange.start))) 结束 \(String(describing: CMTimeGetSeconds(self.playeTimeRange.end)))")
  875. let end3: TimeInterval = Date().timeIntervalSince1970
  876. self.playerView.play(pauseFirstFrame: false, playeTimeRange: CMTimeRange(start: self.playeTimeRange.start, end: self.playeTimeRange.end))
  877. let end4: TimeInterval = Date().timeIntervalSince1970
  878. BFLog(message: " playerView.play tiskskskskme \(end4 - end3)")
  879. // 6,进度回调
  880. self.playerView.progress = { [weak self] currentTime, tatolTime, _ in
  881. if(CMTimeGetSeconds(self?.playeTimeRange.duration ?? .zero) <= 0.0){
  882. BFLog(message: "时长错误!!!!")
  883. return
  884. }
  885. // 更新进度
  886. let progress = (currentTime - CMTimeGetSeconds(self?.playeTimeRange.start ?? .zero)) / CMTimeGetSeconds(self?.playeTimeRange.duration ?? .zero)
  887. BFLog(message: "\(currentTime) \(tatolTime) 显示播放器进度为: \(progress)")
  888. self?.stuckPointCuttingView.updateProgress(progress: CGFloat(progress))
  889. if self?.synchroMarskView.superview != nil {
  890. self?.synchroMarskView.removeMarskView()
  891. }
  892. }
  893. }
  894. }
  895. }
  896. deinit {
  897. musicNameLab.stop()
  898. // playerView.pause()
  899. // 取消所有的导出
  900. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  901. exportSession.cancelExport()
  902. }
  903. BFLog(1, message: "卡点视频预览界面release")
  904. }
  905. }
  906. // MARK: - 视频渲染相关逻辑方法
  907. extension PQStuckPointEditerController {
  908. /// 分割视频 这里只设置视频类型的 in 和 out 并不设置显示的开始和结束时间 mp4 ,png ,png ,mp4
  909. /// - Parameter section: 当前段
  910. /// - Parameter stuckPoints: 用户选择的,或推荐的卡点数
  911. /// - Returns: 返回分割后的所有 stickers 和卡点数是一致的
  912. func clipVideoMerage(section: PQEditSectionModel, stuckPoints: [Float]) -> [PQEditVisionTrackMaterialsModel] {
  913. var stickers: Array = Array<PQEditVisionTrackMaterialsModel>.init()
  914. // 第二种情况:有视频要进行分割
  915. /*
  916. 1, 确定每个视频素材需要切的段数p
  917. 2, 将所有视频时长相加,得到总视频素材时长L = l1 + l2 + ... + ln
  918. 3, 视频素材a1需要切分的个数clipNum = max (round (kongduan * a1 / L) , 1)
  919. */
  920. // 要补的空位数
  921. let kongduan: Int = Int(stuckPoints.count) - Int(section.sectionTimeline!.visionTrack?.getEnableVisionTrackMaterials().count ?? 0)
  922. // 所有视频总时长
  923. var videoTotalDuration: Float64 = 0.0
  924. for video in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "video") {
  925. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + video.locationPath), options: nil)
  926. videoTotalDuration = videoTotalDuration + Float64(CMTimeGetSeconds(asset.duration))
  927. }
  928. if videoTotalDuration == 0 {
  929. BFLog(message: "视频总时长出现错误!!!!这里应该有视频素材的")
  930. return stickers
  931. }
  932. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  933. if sticker.type == StickerType.VIDEO.rawValue {
  934. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  935. // 要分割的段落
  936. let clipNum = Int(max(round(Double(kongduan) * CMTimeGetSeconds(asset.duration) / videoTotalDuration), 1))
  937. sticker.duration = CMTimeGetSeconds(asset.duration)
  938. BFLog(message: "单个视频\(sticker.locationPath)时长::\(CMTimeGetSeconds(asset.duration)) ,clipNum is:\(clipNum)")
  939. for clipindex in 0 ... clipNum - 1 {
  940. // deep copy sticker model 防止只有一个对象
  941. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  942. // 设置循环模式和适配模式
  943. deepCopySticker?.generateDefaultValues()
  944. deepCopySticker?.model_in = clipindex == 0 ? 0 : CMTimeGetSeconds(asset.duration) / Double(clipNum) * Double(clipindex)
  945. deepCopySticker?.out = (deepCopySticker?.model_in ?? 0) + CMTimeGetSeconds(asset.duration) / Double(clipNum)
  946. if (deepCopySticker?.model_in ?? 0) >= CMTimeGetSeconds(asset.duration) || (deepCopySticker?.out ?? 0) >= CMTimeGetSeconds(asset.duration) {
  947. deepCopySticker?.model_in = CMTimeGetSeconds(asset.duration) - CMTimeGetSeconds(asset.duration) / Double(clipNum)
  948. deepCopySticker?.out = CMTimeGetSeconds(asset.duration)
  949. }
  950. BFLog(message: " crilp is in \(deepCopySticker?.model_in ?? 0) out \(deepCopySticker?.out ?? 0) 总时长\(CMTimeGetSeconds(asset.duration))")
  951. if deepCopySticker != nil {
  952. stickers.append(deepCopySticker!)
  953. }
  954. }
  955. } else if sticker.type == StickerType.IMAGE.rawValue {
  956. sticker.generateDefaultValues()
  957. stickers.append(sticker)
  958. }
  959. }
  960. return stickers
  961. }
  962. /// 创建sticker
  963. /// - Parameters:
  964. /// - sections: 项目所有段落数据信息
  965. /// - inputSize: 画布大小
  966. /// - Returns: filters 数据 播放器可直接使用
  967. func createStickers(sections: List<PQEditSectionModel>, inputSize _: CGSize = .zero, model: createStickersModel = .createStickersModelPoint) -> [PQEditVisionTrackMaterialsModel] {
  968. // 推荐卡点数
  969. let beginDecoderTime: TimeInterval = Date().timeIntervalSince1970
  970. // 保存滤镜对象数据
  971. var stickers: Array = Array<PQEditVisionTrackMaterialsModel>.init()
  972. for section in sections {
  973. if section.sectionType == "normal" {
  974. // 第一种情况:全是图片,三种模式都进行图片回环播放
  975. if section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "video").count == 0, section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials(type: "image").count > 0 {
  976. for (index, point) in finallyStuckPoints.enumerated() {
  977. let sticker: PQEditVisionTrackMaterialsModel = section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials()[index % section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials().count]
  978. BFLog(message: "stickerlocationPath sticker : \(sticker.locationPath)")
  979. //
  980. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  981. if deepCopySticker!.type == StickerType.IMAGE.rawValue {
  982. if index + 1 < finallyStuckPoints.count {
  983. deepCopySticker!.timelineIn = Float64("\(finallyStuckPoints[index])") ?? 0.0
  984. deepCopySticker!.timelineOut = Float64("\(finallyStuckPoints[index + 1])") ?? 0.0
  985. if deepCopySticker != nil {
  986. deepCopySticker?.generateDefaultValues()
  987. stickers.append(deepCopySticker!)
  988. BFLog(1, message: "测试人员index is 纯图片 timelineOut:\(deepCopySticker!.timelineIn) timelineOut :\(deepCopySticker!.timelineOut)")
  989. }
  990. }
  991. }
  992. }
  993. } else { // 第二种情况:视频 + 图片情况、视频要分段+图片按卡点时长创建
  994. if model == .createStickersModelPoint { // 跳跃卡点
  995. // 第二种情况:有视频要进行分割
  996. let clipFilters = clipVideoMerage(section: section, stuckPoints: finallyStuckPoints)
  997. for (index, point) in finallyStuckPoints.enumerated() {
  998. BFLog(message: "aaaaaindexindeindexxindexindexindex \(index) \(point)")
  999. if index + 1 < finallyStuckPoints.count, index < clipFilters.count {
  1000. BFLog(message: "bbbbbindexindeindexxindexindexindex \(index) \(point)")
  1001. let sticker: PQEditVisionTrackMaterialsModel = clipFilters[index]
  1002. sticker.timelineIn = Float64("\(finallyStuckPoints[index])") ?? 0.0
  1003. sticker.timelineOut = Float64("\(finallyStuckPoints[index + 1])") ?? 0.0
  1004. // 卡点的时间 > in out 值 这里就会出现鬼畜效果
  1005. let timelineInterval = sticker.timelineOut - sticker.timelineIn
  1006. let inOutInterval = sticker.out - sticker.model_in
  1007. if timelineInterval > inOutInterval {
  1008. BFLog(message: "实际要显示卡点时长\(timelineInterval) 素材裁剪时长:\(inOutInterval)")
  1009. sticker.out = sticker.model_in + timelineInterval
  1010. // 下面只是 LOG 方便查问题
  1011. let stickerInOut = sticker.out - sticker.model_in
  1012. let stickerTimelineInOut = sticker.timelineOut - sticker.timelineIn
  1013. if stickerInOut != stickerTimelineInOut {
  1014. BFLog(message: "sticker.timelineIn \(sticker.timelineIn) stickerTimelineInOut is\(stickerTimelineInOut) stickerInOut is\(stickerInOut) 相差\(stickerTimelineInOut - stickerInOut)")
  1015. }
  1016. }
  1017. // out > 素材的总时长in out 进行前移操作
  1018. let offsetAssetDuration = sticker.out - sticker.duration
  1019. if offsetAssetDuration > 0 {
  1020. sticker.model_in = sticker.model_in - offsetAssetDuration
  1021. sticker.out = sticker.out - offsetAssetDuration
  1022. }
  1023. BFLog(message: "测试人员index is \(index)分割后 创建 filter timelineIn :\(sticker.timelineIn) timelineOut :\(sticker.timelineOut) in :\(sticker.model_in) out:\(sticker.out) type is \(sticker.type) 显示总时长为:\(sticker.timelineOut - sticker.timelineIn) 裁剪总时长\(sticker.out - sticker.model_in)")
  1024. stickers.append(sticker)
  1025. }
  1026. }
  1027. } else if model == .createStickersModelOnlyMusic || model == .createStickersModelSpeed { // 仅音乐 和 快慢速卡点
  1028. BFLog(message: "stuckPoints count is \(finallyStuckPoints.count)")
  1029. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  1030. if sticker.type == StickerType.VIDEO.rawValue {
  1031. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  1032. BFLog(message: "单个视频\(sticker.locationPath)时长::\(CMTimeGetSeconds(asset.duration)) ,clipNum is:\(sticker.clipCount)")
  1033. var lastOutTime: Float64 = 0.0
  1034. for _ in 0 ... sticker.clipCount {
  1035. // deep copy sticker model 防止只有一个对象
  1036. let deepCopyStickerDecoderTime: TimeInterval = Date().timeIntervalSince1970
  1037. let deepCopySticker:PQEditVisionTrackMaterialsModel? = sticker.copy() as? PQEditVisionTrackMaterialsModel
  1038. BFLog(message: "生成stickers 总时长为 aaa\(Date().timeIntervalSince1970 - deepCopyStickerDecoderTime)")
  1039. // 设置循环模式和适配模式
  1040. deepCopySticker?.generateDefaultValues()
  1041. deepCopySticker?.materialDurationFit?.fitType = adapterMode.staticFrame.rawValue
  1042. // 当前分段的速度
  1043. var tempSpeed: Float = 1.0
  1044. if model == .createStickersModelSpeed {
  1045. tempSpeed = (stickers.count % 2) == 0 ? maxSpeed : minSpeed
  1046. }
  1047. if stickers.count + 1 < finallyStuckPoints.count {
  1048. deepCopySticker?.speedRate = tempSpeed
  1049. // 定义临时使用的变量
  1050. // 素材显示的开始时间和结束时间
  1051. let tempTimelineIn:Float64 = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count])) ?? 0.0
  1052. let timelineOut:Float64 = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count + 1])) ?? 0.0
  1053. // 素材分割的开始时间和结束时间
  1054. let tempModel_In = lastOutTime
  1055. var tempOut = lastOutTime + Float64(tempSpeed) * (timelineOut - tempTimelineIn)
  1056. // 处理最后一点视频素材不够卡点时长 e.g. 0.3 卡点时长0.5
  1057. if tempOut > CMTimeGetSeconds(asset.duration) {
  1058. BFLog(message: "最后一点视频素材不够卡点时长要做变速C处理 差\(tempOut - CMTimeGetSeconds(asset.duration))")
  1059. // 最后一点素材时长
  1060. let lastAssetDuration = CMTimeGetSeconds(asset.duration) - lastOutTime
  1061. let pointDuration = timelineOut - tempTimelineIn
  1062. // 要适应到卡点内要使用的C速度
  1063. let needSpeed = lastAssetDuration / pointDuration
  1064. // 当前卡点段为快速
  1065. if tempSpeed >= 1 {
  1066. if needSpeed >= 0.4 * Double(tempSpeed) {
  1067. deepCopySticker?.speedRate = Float(needSpeed)
  1068. } else {
  1069. continue
  1070. }
  1071. } else { // 当前卡点段为慢速
  1072. if needSpeed >= 0.4 * Double(tempSpeed) && needSpeed >= 0.2 {
  1073. deepCopySticker?.speedRate = Float(needSpeed)
  1074. } else {
  1075. continue
  1076. }
  1077. }
  1078. tempOut = CMTimeGetSeconds(asset.duration)
  1079. }
  1080. deepCopySticker?.model_in = tempModel_In
  1081. deepCopySticker?.out = tempOut
  1082. deepCopySticker?.timelineIn = tempTimelineIn
  1083. deepCopySticker?.timelineOut = timelineOut
  1084. lastOutTime = deepCopySticker?.out ?? 0
  1085. }
  1086. BFLog(1, message: "测试人员创建 sticker crilp is in 视频 \(String(format: "%.6f", deepCopySticker?.model_in ?? 0)) out \(String(format: "%.6f", deepCopySticker?.out ?? 0)) ,分段素材时长:\(String(format: "%.6f", (deepCopySticker?.out ?? 0) - (deepCopySticker?.model_in ?? 0))) ,分段显示时长:\(String(format: "%.6f", (deepCopySticker?.timelineOut ?? 0) - (deepCopySticker?.timelineIn ?? 0))), 视频素材原时长\(CMTimeGetSeconds(asset.duration)) timelineIN: \(String(format: "%.6f", deepCopySticker?.timelineIn ?? 0)) timelineOUT:\(String(format: "%.6f", deepCopySticker?.timelineOut ?? 0)) speedRate:\(deepCopySticker?.speedRate ?? 0.0)")
  1087. if deepCopySticker != nil {
  1088. stickers.append(deepCopySticker!)
  1089. }
  1090. }
  1091. } else if sticker.type == StickerType.IMAGE.rawValue {
  1092. if stickers.count + 1 >= finallyStuckPoints.count {
  1093. BFLog(message: "数据出现错误!!!查正") // 155.318253
  1094. break
  1095. }
  1096. sticker.generateDefaultValues()
  1097. sticker.timelineIn = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count])) ?? 0.0
  1098. sticker.timelineOut = Float64(String(format: "%.6f",finallyStuckPoints[stickers.count + 1])) ?? 0.0
  1099. stickers.append(sticker)
  1100. BFLog(1, message: "测试人员创建 sticker crilp is in 图片 \(String(format: "%.6f", sticker.model_in)) out \(String(format: "%.6f", sticker.out)) ,分段素材时长:\(String(format: "%.6f", (sticker.out) - (sticker.model_in))) ,分段显示时长:\(String(format: "%.6f", (sticker.timelineOut) - (sticker.timelineIn))), timelineIN: \(String(format: "%.6f", sticker.timelineIn)) timelineOUT:\(String(format: "%.6f", sticker.timelineOut)) speedRate:\(sticker.speedRate)")
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. BFLog(message: "生成stickers 总时长为:\(Date().timeIntervalSince1970 - beginDecoderTime)")
  1108. return stickers
  1109. }
  1110. /// 根据档位取最后使用的卡点数据
  1111. /// - Parameter seed: 档位速度
  1112. /// - Returns: 最后使用的卡点
  1113. func getUsedStuckPoint(seed: Int) -> Array<Float> {
  1114. // 推荐卡点数
  1115. var stuckPoints: Array = Array<Float>.init()
  1116. var pointsTemp = Array<Float>.init()
  1117. //
  1118. // 最后一个卡点时间(原推荐卡点的倒数第二位时间)
  1119. let lastPoint = stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 1]
  1120. for (index, dunshu) in stuckPointMusicData!.rhythmSdata[0].pointTimes.enumerated() {
  1121. if dunshu >= Int64((stuckPointMusicData?.startTime ?? 0) * Float64(BASE_FILTER_TIMESCALE)) && dunshu < lastPoint {
  1122. let savePointStr = String(format: "%.6f", Float(dunshu) / Float(BASE_FILTER_TIMESCALE))
  1123. BFLog(message: "原所有卡点数:\(index) \(savePointStr)")
  1124. pointsTemp.append(Float(savePointStr) ?? 0.0)
  1125. }
  1126. }
  1127. /*
  1128. 一,快慢速模式下取卡点 2 3 4
  1129. 二,跳跃卡点模式下根据不同速度 取卡点 1,2,3
  1130. 快节奏为选中区域的所有点位,即0,1,2,3,4 5 6 7 8 9 10 ……
  1131. 适中为每两个点位取一个,即0,2,4,6……
  1132. 慢节奏为每三个点位取一个,即0,3,6,9……
  1133. */
  1134. // 不丢
  1135. if seed == 1 {
  1136. stuckPoints = pointsTemp
  1137. } else {
  1138. // 根据档位要丢
  1139. for (index, point) in pointsTemp.enumerated() {
  1140. if index % seed == 0 {
  1141. stuckPoints.append(point)
  1142. }
  1143. }
  1144. }
  1145. for point in stuckPoints {
  1146. BFLog(message: "没有 start end 计算后的卡点数\(point)")
  1147. }
  1148. // 若音乐起点至第一个卡点点位之间时长t0<0.3时,此段时长与下一个点位时长合并,故第一段卡点部分时长为t0+d
  1149. if Float(stuckPointMusicData?.startTime ?? 0) - (stuckPoints.first ?? 0.0) < 0.3 {
  1150. if stuckPoints.first != nil {
  1151. stuckPoints.removeFirst()
  1152. }
  1153. }
  1154. stuckPoints.insert(Float(stuckPointMusicData?.startTime ?? 0), at: 0)
  1155. for point in stuckPoints {
  1156. BFLog(message: "有 start end 计算后的卡点数\(point)")
  1157. }
  1158. BFLog(message: "处理节奏后 stuckPoints count is \(stuckPoints.count) seed \(seed), start time:\(stuckPoints.first ?? 0.0),end time:\(stuckPoints.last ?? 0.0) 总时长为:\((stuckPoints.last ?? 0.0) - (stuckPoints.first ?? 0.0))")
  1159. return stuckPoints
  1160. }
  1161. func clipPoint(clipCount: Int, oldPoints: Array<Float>) {
  1162. BFLog(message: "拼接卡点数:\(clipCount)")
  1163. if(clipCount < 0 || oldPoints.count < 2){
  1164. BFLog(message: "clipCount is error!!!! \(clipCount)")
  1165. return
  1166. }
  1167. // 如果是第一次拼接先补第0位
  1168. if finallyStuckPoints.count == 0 {
  1169. finallyStuckPoints.append(stuckPointsTemp.first ?? 0.0)
  1170. }
  1171. for i in finallyStuckPoints.count ... clipCount + finallyStuckPoints.count {
  1172. if (i % (oldPoints.count - 1)) != 1 {
  1173. let value = String(format: "%.6f", finallyStuckPoints[i - 1] + oldPoints[((i-1) % (oldPoints.count - 1)) + 1] - oldPoints[((i - 2) % (oldPoints.count - 1)) + 1])
  1174. finallyStuckPoints.append(Float(value) ?? 0.0)
  1175. } else {
  1176. let value = String(format: "%.6f", finallyStuckPoints[i - 1] + oldPoints[1] - oldPoints[0])
  1177. finallyStuckPoints.append(Float(value) ?? 0.0)
  1178. }
  1179. }
  1180. }
  1181. /// 根据不同模式model, maxSpeed ,minSpeed, self?.stuckPointMusicData?.speed 档位,生成音乐时长和最终使用的卡点信息
  1182. func dealParameter(model: createStickersModel) {
  1183. // 清空上一次使用的卡点数据
  1184. finallyStuckPoints.removeAll()
  1185. // 已经取到的视频素材总长度,用于和原视频素材时长做对比,不够多加一个点
  1186. var useAssestDuration: Float = 0.0
  1187. switch model {
  1188. case .createStickersModelPoint: // 跳跃卡点
  1189. stuckPointsTemp = getUsedStuckPoint(seed: stuckPointMusicData?.speed ?? 0)
  1190. // 要拼接的段数
  1191. var clipNum: Int = 0
  1192. var i: Int = 0
  1193. // L/(n+1) L -原视觉素材总时长 n-抛留倍数 lastJumpSpeedSelectIndex 是位置 对应的值要+1
  1194. // 根据公式计划出的总时长
  1195. let jumpTime = Float(selectedTotalDuration) / Float(maxSpeed + 1)
  1196. // 只有图片素材时会为0
  1197. if jumpTime > 0 {
  1198. while useAssestDuration < Float(jumpTime) {
  1199. // 回环从头取\
  1200. if i + 1 >= stuckPointsTemp.count {
  1201. i = 0
  1202. }
  1203. // 快速段
  1204. let LA = (stuckPointsTemp[i + 1] - stuckPointsTemp[i])
  1205. useAssestDuration = useAssestDuration + Float(LA)
  1206. i = i + 1
  1207. clipNum = clipNum + 1
  1208. }
  1209. // 拼接要使用的卡点信息
  1210. clipPoint(clipCount: clipNum, oldPoints: stuckPointsTemp)
  1211. }
  1212. break
  1213. case .createStickersModelSpeed, .createStickersModelOnlyMusic: // 快慢速
  1214. // 快慢速 (2:快节奏,3:适中,4:慢节奏)
  1215. var tempMaxSpeed: Float = 1
  1216. var tempMinSpeed: Float = 1
  1217. //速度有为0 会出现在切换模式时,目前是共用一个参数值,会清掉老值 TODO
  1218. if((maxSpeed == 0.0 && minSpeed == 0.0) && selectedDataCount != selectedImageDataCount && model == .createStickersModelSpeed){
  1219. BFLog(message: "速度参数有错误 要重新计算!!!")
  1220. dealWithDataSuccess()
  1221. return
  1222. }
  1223. if model == .createStickersModelSpeed {
  1224. // 改变速率,.只有快慢速且非只有图片素材时自动+1处理
  1225. if model == .createStickersModelSpeed && selectedDataCount != selectedImageDataCount {
  1226. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0) + 1)
  1227. } else {
  1228. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0))
  1229. }
  1230. tempMaxSpeed = maxSpeed
  1231. tempMinSpeed = minSpeed
  1232. } else {
  1233. stuckPointsTemp = getUsedStuckPoint(seed: (stuckPointMusicData?.speed ?? 0))
  1234. }
  1235. /*
  1236. - A-视频中的快速片段
  1237. - B-视频中的慢速片段
  1238. - d-在一档下音乐每个点位时长
  1239. - n-不同音乐档位对应的d倍数,快节奏时,n=1;适中时,n=3;慢节奏时,n=5
  1240. - L-原视觉素材时长
  1241. - x-视频在A片段的播放倍速
  1242. - y-视频在B片段的播放倍速
  1243. */
  1244. // LA=x*n*d,LB=y*n*d (n=1/3/5) 注:视频经过快慢速处理后的总时长约=L*2/(x+y)
  1245. BFLog(message: "Ax快速为:\(tempMaxSpeed) By慢速为:\(tempMinSpeed) 档位 N为:\(stuckPointMusicData?.speed ?? 0) 使用的卡点总数:\(stuckPointsTemp.count)")
  1246. // 使用新方法取使用的卡点数据
  1247. for section in projectModel.sData?.sections ?? List() {
  1248. if section.sectionType == "normal" {
  1249. for sticker in section.sectionTimeline!.visionTrack!.getEnableVisionTrackMaterials() {
  1250. if sticker.type == StickerType.VIDEO.rawValue {
  1251. let asset: AVURLAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + sticker.locationPath), options: nil)
  1252. let assetDuration = Float(CMTimeGetSeconds(asset.duration))
  1253. BFLog(message: "输入素材时长 \(assetDuration)")
  1254. if(finallyStuckPoints.count == 0){
  1255. finallyStuckPoints.append(stuckPointsTemp[0])
  1256. }
  1257. var j = finallyStuckPoints.count
  1258. // 添加卡点的段数 用于判断当前卡点是快/慢速
  1259. var pointCount:Int = 0
  1260. // 已经取到的视频素材总长度,用于和原视频素材时长做对比,不够多加一个卡点
  1261. var useAssestDurationTemp: Float = 0.0
  1262. while useAssestDurationTemp < assetDuration {
  1263. //当前段的应该使用的速度 A/B
  1264. let useSpeed = (pointCount % 2 == 0 ) ? tempMaxSpeed : tempMinSpeed
  1265. // 计算卡点
  1266. //要添加的卡点数值
  1267. var sub:Float = 0.0
  1268. if stuckPointsTemp.count > 2 {
  1269. if ((j - 1) % (stuckPointsTemp.count - 1)) != 0{
  1270. sub = stuckPointsTemp[((j - 1) % (stuckPointsTemp.count-1)) + 1] - stuckPointsTemp[(j - 1) % (stuckPointsTemp.count - 1)]
  1271. }else {
  1272. sub = stuckPointsTemp[1] - stuckPointsTemp[0]
  1273. }
  1274. finallyStuckPoints.append(finallyStuckPoints[j - 1] + sub)
  1275. j += 1
  1276. }
  1277. useAssestDurationTemp += sub * useSpeed
  1278. if(useAssestDurationTemp > assetDuration){
  1279. useAssestDurationTemp -= sub * useSpeed
  1280. break
  1281. }
  1282. pointCount += 1
  1283. FilterLog(message: "finallyStuckPoints last ;\((finallyStuckPoints.last ?? 0.0) - (finallyStuckPoints.first ?? 0.0)), tmp:\(useAssestDurationTemp)")
  1284. }
  1285. // 2拼接要使用的卡点信息
  1286. sticker.clipCount = pointCount
  1287. if stuckPointsTemp.count < 1 {
  1288. //todo 和产品沟通提示
  1289. BFLog(message: "卡点数据有错误!!!")
  1290. return
  1291. }
  1292. BFLog(message: "finallyStuckPoints\(finallyStuckPoints)")
  1293. // 3,多补一个卡点 做 C级 速处理,要根据条件不满足 要删除最后一位,
  1294. if useAssestDurationTemp < assetDuration {
  1295. // 下一个卡的的速度性质快、慢
  1296. var tempSpeed: Float = 1.0
  1297. if model == .createStickersModelSpeed {
  1298. tempSpeed = (sticker.clipCount) % 2 == 0 ? maxSpeed : minSpeed
  1299. }
  1300. // 最后一点素材时长
  1301. let lastAssetDuration = Float(CMTimeGetSeconds(asset.duration)) - useAssestDurationTemp
  1302. let lastPointIndex = (sticker.clipCount % stuckPointsTemp.count)
  1303. // 两个卡点
  1304. let a: Float = stuckPointsTemp[lastPointIndex]
  1305. var b: Float = 0.0
  1306. if lastPointIndex + 1 < stuckPointsTemp.count {
  1307. b = stuckPointsTemp[lastPointIndex + 1]
  1308. let pointDuration = b - a
  1309. // 要适应到卡点内要使用的C速度
  1310. let needSpeed = lastAssetDuration / pointDuration
  1311. // 当前卡点段为快速
  1312. if tempSpeed >= 1 {
  1313. if needSpeed < 0.4 * tempSpeed {
  1314. BFLog(message: "条件不满足不用补位 删除多加的一位")
  1315. finallyStuckPoints.removeLast()
  1316. }
  1317. } else { // 当前卡点段为慢速
  1318. if needSpeed >= 0.4 * tempSpeed && needSpeed >= 0.2 {
  1319. // 查找使用的最后一个卡点在原数组中的位置
  1320. } else {
  1321. BFLog(message: "条件不满足不用补位 删除多加的一位")
  1322. finallyStuckPoints.removeLast()
  1323. }
  1324. }
  1325. }
  1326. }else {
  1327. //出现在第一个卡点X 倍速 > 原素材
  1328. finallyStuckPoints.removeLast()
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }
  1334. break
  1335. }
  1336. // 拼接图片所使用的时长.选择一组图片 按图片数量计算卡点的总时长
  1337. if selectedImageDataCount > 0 {
  1338. clipPoint(clipCount: selectedImageDataCount - 1, oldPoints: stuckPointsTemp)
  1339. }
  1340. // 全是图片时数组里放着的一定都是图片的使用的卡点
  1341. // 定义一次循环的总时长
  1342. var oneSelectImageDuration: Float = 0.0
  1343. if selectedDataCount == selectedImageDataCount {
  1344. oneSelectImageDuration = (finallyStuckPoints.last ?? 0) - (finallyStuckPoints.first ?? 0)
  1345. }
  1346. // 3)素材全是图片处理
  1347. if selectedDataCount == selectedImageDataCount{
  1348. // lastCyclesSelectIndex != -1 已经设置过循环次数 应该是手动设置的值
  1349. if lastCyclesSelectIndex != -1 {
  1350. // 纯图片时 已经默认添加一次循环 所以要用lastCyclesSelectIndex - 1
  1351. if(lastCyclesSelectIndex != 0){
  1352. clipPoint(clipCount: selectedImageDataCount * lastCyclesSelectIndex - 1, oldPoints: stuckPointsTemp)
  1353. }
  1354. } else {
  1355. if(oneSelectImageDuration < 10 ){
  1356. lastCyclesSelectIndex = 0
  1357. while oneSelectImageDuration < 10 {
  1358. // 不够10S 时 一次加图片数量的卡点数
  1359. clipPoint(clipCount: selectedImageDataCount - 1, oldPoints: stuckPointsTemp)
  1360. oneSelectImageDuration = Float((finallyStuckPoints.last ?? 0) - (finallyStuckPoints.first ?? 0))
  1361. lastCyclesSelectIndex = lastCyclesSelectIndex + 1
  1362. }
  1363. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false,enableInsert: true)
  1364. }else{
  1365. lastCyclesSelectIndex = 0
  1366. }
  1367. }
  1368. }
  1369. // 设置速度选择的位置
  1370. if speedSettingView.viewType == 1 {
  1371. speedSettingView.setSelectItem(index: lastSpeedSelectIndex, isSettingPlayer: false)
  1372. } else if speedSettingView.viewType == 2 {
  1373. speedSettingView.setSelectItem(index: lastJumpSpeedSelectIndex, isSettingPlayer: false)
  1374. } else if speedSettingView.viewType == 3 {
  1375. if lastCyclesSelectIndex != -1 {
  1376. speedSettingView.setSelectItem(index: lastCyclesSelectIndex, isSettingPlayer: false)
  1377. } else {
  1378. speedSettingView.setSelectItem(index: 0, isSettingPlayer: false)
  1379. }
  1380. }
  1381. // 四,背景音乐时长处理)计算最后使用的音频时长, 如果不用拼接音频时长度是卡点的倒数第二位时间
  1382. let asset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + (stuckPointMusicData?.localPath ?? "")), options: nil)
  1383. // 原推荐卡点的倒数第二位时间
  1384. let lastSecondPoint = Float((stuckPointMusicData!.rhythmSdata[0].pointTimes[stuckPointMusicData!.rhythmSdata[0].pointTimes.count - 2])) / Float(BASE_FILTER_TIMESCALE)
  1385. finallyUserAudioTime = Float(lastSecondPoint)
  1386. if (finallyStuckPoints.last ?? 0) > Float(CMTimeGetSeconds(asset.duration)) {
  1387. finallyUserAudioTime = Float(finallyStuckPoints.last ?? 0) + (Float(CMTimeGetSeconds(asset.duration)) - Float(lastSecondPoint))
  1388. }
  1389. playeTimeRange = CMTimeRange(start: CMTime(value: CMTimeValue(Float64(finallyStuckPoints.first ?? 0) * Float64(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE), end: CMTime(value: CMTimeValue((Float64(finallyStuckPoints.last ?? 0)) * Float64(BASE_FILTER_TIMESCALE)), timescale: BASE_FILTER_TIMESCALE))
  1390. for (index, usePoint) in finallyStuckPoints.enumerated() {
  1391. BFLog(message: "测试人员最后使用的卡点信息 \(index) : \(usePoint)")
  1392. }
  1393. BFLog(message: "计算后给播放器使用的开始:\(CMTimeGetSeconds(playeTimeRange.start)) 结束时间\(CMTimeGetSeconds(playeTimeRange.end)) 播放总时长:\(CMTimeGetSeconds(playeTimeRange.end) - CMTimeGetSeconds(playeTimeRange.start))")
  1394. }
  1395. }
  1396. // MARK: - 同步/下载素材相关
  1397. /// 同步/下载素材相关
  1398. extension PQStuckPointEditerController {
  1399. /// 同步音乐相关数据
  1400. /// - Returns: <#description#>
  1401. func synchroMusicInfoData() {
  1402. if (stuckPointMusicData?.rhythmSdata.count ?? 0) <= 0 {
  1403. if synchroMarskView.superview == nil {
  1404. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1405. synchroMarskView.show()
  1406. }
  1407. PQStuckPointViewModel.stuckPointMusicDetailData(musicId: stuckPointMusicData?.musicId ?? "", originType: stuckPointMusicData?.originType ?? 1) { [weak self] newMusicData, _ in
  1408. if newMusicData != nil, (newMusicData?.rhythmSdata.count ?? 0) > 0 {
  1409. self?.isStuckPointDataSuccess = true
  1410. self?.stuckPointMusicData?.rhythmSdata = newMusicData?.rhythmSdata ?? []
  1411. self?.stuckPointMusicData?.startTime = newMusicData?.startTime ?? 0
  1412. self?.stuckPointMusicData?.endTime = newMusicData?.endTime ?? 0
  1413. if newMusicData?.speed != nil {
  1414. self?.stuckPointMusicData?.speed = newMusicData?.speed ?? 2
  1415. }
  1416. if self?.stuckPointMusicData?.localPath == nil || (self?.stuckPointMusicData?.localPath?.count ?? 0) > 0 {
  1417. PQDownloadManager.downLoadFile(url: self?.stuckPointMusicData?.musicPath ?? "") { [weak self] filePath, error in
  1418. if error == nil, filePath != nil {
  1419. self?.isSynchroMusicInfoSuccess = true
  1420. self?.stuckPointMusicData?.localPath = filePath?.replacingOccurrences(of: documensDirectory, with: "")
  1421. // 处理所有数据完成
  1422. self?.dealWithDataSuccess()
  1423. }
  1424. if self?.synchroMarskView.superview != nil {
  1425. self?.synchroMarskView.removeMarskView()
  1426. }
  1427. }
  1428. } else {
  1429. self?.isSynchroMusicInfoSuccess = true
  1430. // 处理所有数据完成
  1431. self?.dealWithDataSuccess()
  1432. }
  1433. // 添加子视图
  1434. self?.addSubViews()
  1435. } else {
  1436. if self?.synchroMarskView.superview != nil {
  1437. self?.synchroMarskView.removeMarskView()
  1438. }
  1439. }
  1440. }
  1441. } else if stuckPointMusicData?.localPath == nil || (stuckPointMusicData?.localPath?.count ?? 0) > 0 {
  1442. if synchroMarskView.superview == nil {
  1443. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1444. synchroMarskView.show()
  1445. }
  1446. isStuckPointDataSuccess = true
  1447. PQDownloadManager.downLoadFile(url: stuckPointMusicData?.musicPath ?? "") { [weak self] filePath, error in
  1448. if error == nil, filePath != nil {
  1449. self?.isSynchroMusicInfoSuccess = true
  1450. self?.stuckPointMusicData?.localPath = filePath?.replacingOccurrences(of: documensDirectory, with: "")
  1451. // 处理所有数据完成
  1452. self?.dealWithDataSuccess()
  1453. } else {
  1454. if self?.synchroMarskView.superview != nil {
  1455. self?.synchroMarskView.removeMarskView()
  1456. }
  1457. // PQUploadRemindView.showUploadRemindView(title: nil, attributedTitle: NSAttributedString(string: "加载音乐失败,请重新选择音乐"), summary: "", confirmTitle: nil) { [weak self] _, _ in
  1458. // self?.navigationController?.popViewController(animated: true)
  1459. // }
  1460. }
  1461. }
  1462. } else {
  1463. isStuckPointDataSuccess = true
  1464. // 处理所有数据完成
  1465. dealWithDataSuccess()
  1466. }
  1467. }
  1468. /// 导出相册数据
  1469. /// - Returns: <#description#>
  1470. func exportPhotoData() {
  1471. // 取消所有的导出
  1472. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  1473. exportSession.cancelExport()
  1474. }
  1475. var isHaveVideo: Bool = false
  1476. if selectedPhotoData != nil, (selectedPhotoData?.count ?? 0) > 0 {
  1477. if synchroMarskView.superview == nil {
  1478. UIApplication.shared.keyWindow?.addSubview(synchroMarskView)
  1479. }
  1480. let dispatchGroup = DispatchGroup()
  1481. for photo in selectedPhotoData! {
  1482. if photo.asset != nil, photo.asset?.mediaType == .video {
  1483. if !isHaveVideo {
  1484. isHaveVideo = true
  1485. }
  1486. dispatchGroup.enter()
  1487. PQPHAssetVideoParaseUtil.parasToAVAsset(phAsset: photo.asset!) { avAsset, _, _, _ in
  1488. if avAsset is AVURLAsset {
  1489. // 创建目录
  1490. let fileName = (avAsset as! AVURLAsset).url.absoluteString
  1491. BFLog(message: "video fileName is\(fileName)")
  1492. let tempPhoto = self.selectedPhotoData?.first(where: { material in
  1493. material.asset == photo.asset
  1494. })
  1495. if (fileName.count) > 0 {
  1496. createDirectory(path: photoLibraryDirectory)
  1497. let outFilePath = photoLibraryDirectory + fileName.md5 + ".mp4"
  1498. // 文件存在先删除老文件
  1499. if FileManager.default.fileExists(atPath: outFilePath) {
  1500. do {
  1501. try FileManager.default.removeItem(at: NSURL.fileURL(withPath: outFilePath))
  1502. } catch {
  1503. BFLog(message: "导出相册视频-error == \(error)")
  1504. }
  1505. }
  1506. do {
  1507. try FileManager.default.copyItem(atPath: fileName.replacingOccurrences(of: "file:///", with: ""), toPath: outFilePath)
  1508. print("Success to copy file.")
  1509. } catch {
  1510. print("Failed to copy file.")
  1511. }
  1512. tempPhoto?.locationPath = outFilePath.replacingOccurrences(of: documensDirectory, with: "")
  1513. BFLog(message: "导出视频相册地址为 \(String(describing: tempPhoto?.locationPath))")
  1514. dispatchGroup.leave()
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. dispatchGroup.notify(queue: DispatchQueue.main) { [weak self] in
  1521. self?.isExportVideosSuccess = true
  1522. BFLog(message: "所有相册视频导出成功")
  1523. // 处理所有数据完成
  1524. if isHaveVideo {
  1525. self?.dealWithDataSuccess()
  1526. }
  1527. }
  1528. // 只有图片
  1529. if !isHaveVideo {
  1530. isExportVideosSuccess = true
  1531. BFLog(message: "所有相册视频导出成功")
  1532. dealWithDataSuccess()
  1533. }
  1534. }
  1535. }
  1536. /// 处理所有数据完成
  1537. /// - Returns: <#description#>
  1538. func dealWithDataSuccess() {
  1539. BFLog(message: "三组参数:\(isSynchroMusicInfoSuccess) \(isStuckPointDataSuccess) \(isExportVideosSuccess)")
  1540. if !isSynchroMusicInfoSuccess || !isStuckPointDataSuccess || !isExportVideosSuccess {
  1541. return
  1542. }
  1543. createPorjectData()
  1544. BFLog(message: "界面编辑界面时参数 选择素材时长:\(selectedTotalDuration) 选择素材总数:\(selectedDataCount) 选择图片总数\(selectedImageDataCount) 再创建类型:\(String(describing: reCreateVideoData?.rhythmMode))")
  1545. // 1 生成默认参数值
  1546. /*
  1547. - 当素材总时长∈[0-6)s 时,提示推荐仅配乐模式 or 快慢速模式
  1548. - 当素材总时长∈[6-80)s 时,卡点抛留倍数为1x,即留1抛1
  1549. - 当素材总时长∈[80,120)s 时,卡点抛留倍数为2x,即留1抛2
  1550. - 当素材总时长∈[120,160)s 时,卡点抛留倍数为3x,即留1抛3
  1551. - 当素材总时长∈[160,200)s 时,卡点抛留倍数为4x,即留1抛4
  1552. - 当素材总时长∈[200,240)s 时,卡点抛留倍数为5x,即留1抛5
  1553. - 当素材总时长∈[240,∞)s 时,卡点抛留倍数为5x,即留1抛5
  1554. */
  1555. // 1.1) 生成跳跃卡点的默认值
  1556. if selectedTotalDuration >= 6 && selectedTotalDuration < 80 {
  1557. lastJumpSpeedSelectIndex = 0
  1558. } else if selectedTotalDuration >= 80 && selectedTotalDuration < 120 {
  1559. lastJumpSpeedSelectIndex = 1
  1560. } else if selectedTotalDuration >= 120 && selectedTotalDuration < 160 {
  1561. lastJumpSpeedSelectIndex = 2
  1562. } else if selectedTotalDuration >= 160 && selectedTotalDuration < 200 {
  1563. lastJumpSpeedSelectIndex = 3
  1564. } else if (selectedTotalDuration >= 200 && selectedTotalDuration < 240) || selectedTotalDuration >= 240 {
  1565. lastJumpSpeedSelectIndex = 4
  1566. }
  1567. /* 默认进入快慢速模式
  1568. - 当素材总时长∈[120,144]s 时,快慢速处理方式:快速为 6x,慢速为 1.2x,效果是快&快
  1569. - 当素材总时长∈[70,120)s 时,快慢速处理方式:快速为5x,慢速为 1x,效果是快&正常
  1570. - 当素材总时长∈[56,70)s 时,快慢速处理方式:快速为3x,慢速为 0.5x,效果是快&慢
  1571. - 当素材总时长∈[17.5,56)s 时,快慢速处理方式:快速为 2.4x,慢速为 0.4x,效果是快&慢
  1572. - 当素材总时长∈[10.5,17.5)s 时,快慢速处理方式:快速为 1.8x,慢速为 0.3x,效果是快&慢
  1573. - 当素材总时长∈(0,10.5)s 时,快慢速处理方式:快速为 1x,慢速为 0.2x,效果是正常&慢
  1574. */
  1575. // 1.2)生成快慢速的默认值
  1576. if selectedTotalDuration >= 120 && selectedTotalDuration <= 144 || selectedTotalDuration > 144 {
  1577. lastSpeedSelectIndex = 5
  1578. } else if selectedTotalDuration >= 70 && selectedTotalDuration < 120 {
  1579. lastSpeedSelectIndex = 4
  1580. } else if selectedTotalDuration >= 56 && selectedTotalDuration < 70 {
  1581. lastSpeedSelectIndex = 3
  1582. } else if selectedTotalDuration >= 17.5 && selectedTotalDuration < 56 {
  1583. lastSpeedSelectIndex = 2
  1584. } else if selectedTotalDuration >= 10.5 && selectedTotalDuration < 17.5 {
  1585. lastSpeedSelectIndex = 1
  1586. } else if selectedTotalDuration > 0 && selectedTotalDuration < 10.5 {
  1587. lastSpeedSelectIndex = 0
  1588. }
  1589. // 如果是再创作进来的安原视频的模式
  1590. if reCreateVideoData != nil {
  1591. BFLog(message: "是再创作进来的 \(reCreateVideoData!.rhythmMode)")
  1592. switch reCreateVideoData!.rhythmMode {
  1593. case 1:
  1594. editModelClick(sender: jumpPointBtn, reportLog: false)
  1595. break
  1596. case 2:
  1597. editModelClick(sender: speedStuckBtn, reportLog: false)
  1598. break
  1599. case 3:
  1600. editModelClick(sender: onlyMusicBtn, reportLog: false)
  1601. break
  1602. default: break
  1603. }
  1604. return
  1605. }
  1606. // 跳跃卡点不可用
  1607. if selectedTotalDuration < 6 && selectedDataCount != selectedImageDataCount {
  1608. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_disable"), for: .normal)
  1609. jumpPointBtn.setImage(UIImage().BF_Image(named: "jumpPoint_disable"), for: .selected)
  1610. jumpPointBtnGif.isHidden = true
  1611. }
  1612. /*
  1613. 文档规则 https://w42nne6hzg.feishu.cn/docs/doccnQZm1uCfkU4QtJb5fLxYk4d#
  1614. */
  1615. // 2,根据所选择所有素材时长进入默认模式
  1616. // 全是图片
  1617. if selectedDataCount == selectedImageDataCount {
  1618. BFLog(message: "全是图片 \(selectedDataCount) \(selectedImageDataCount)")
  1619. // 默认进入跳跃卡点模式
  1620. editModelClick(sender: jumpPointBtn, reportLog: false)
  1621. } else {
  1622. // 默认进入快慢速模式
  1623. if selectedTotalDuration > 0 && selectedTotalDuration <= 144 {
  1624. editModelClick(sender: speedStuckBtn, reportLog: false)
  1625. } else {
  1626. // 默认进入卡点模式
  1627. editModelClick(sender: jumpPointBtn, reportLog: false)
  1628. }
  1629. }
  1630. }
  1631. }