PQStuckPointEditerController.swift 97 KB

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