SwiftDubbingLibPlugin.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import Flutter
  2. import UIKit
  3. import AVFoundation
  4. private let timerInterval: Double = 0.03
  5. private let preTime: Double = 0.3
  6. private let preLag: Double = 0.15
  7. enum DubbingStatus {
  8. case stop, record, playRecord
  9. }
  10. public class SwiftDubbingLibPlugin: NSObject, FlutterPlugin {
  11. var registrar: FlutterPluginRegistrar!
  12. var channel: FlutterMethodChannel!
  13. var result: FlutterResult? = nil
  14. /// 当前界面配音状态
  15. var status: DubbingStatus = .stop
  16. var isRecording = false
  17. var audioRecorder: AVAudioRecorder?
  18. var audioPlayer: AVAudioPlayer?
  19. var initFlag: Bool = false
  20. public static func register(with registrar: FlutterPluginRegistrar) {
  21. let channel = FlutterMethodChannel(name: "dubbing_lib", binaryMessenger: registrar.messenger())
  22. let instance = SwiftDubbingLibPlugin()
  23. registrar.addMethodCallDelegate(instance, channel: channel)
  24. instance.channel = channel
  25. instance.registrar = registrar
  26. }
  27. public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
  28. let args = call.arguments as? [String: Any];
  29. self.result = result;
  30. switch call.method {
  31. case "getPlatformVersion":
  32. result("iOS " + UIDevice.current.systemVersion)
  33. break
  34. case "startRecord":
  35. let duration = args!["duration"] as! Int;
  36. let fileName = args!["fileName"] as! String;
  37. let index = args!["index"] as! Int;
  38. let pathAudio = args!["pathAudio"] as! String;
  39. startRecord(pathAudio: pathAudio, index: index, duration: duration, fileName: fileName, result: result)
  40. break
  41. case "playRecordAudio":
  42. let filePath = args!["fileName"] as! String;
  43. playRecord(filePath: filePath, result: result)
  44. break
  45. case "pauseRecordAudio":
  46. audioPlayer?.pause()
  47. result(true)
  48. break
  49. case "startMixinAudio":
  50. let videoId = args!["videoId"] as! String;
  51. let videoPath = args!["videoPath"] as! String;
  52. let bgmPath = args!["bgmPath"] as! String;
  53. let audioPathList = args!["audioDecodePaths"] as! [String];
  54. let startTimeList = args!["startTimeList"] as! [Double];
  55. let pathVideoMixinDir = args!["pathVideoMixin"] as! String;
  56. let outPath = pathVideoMixinDir + "\(videoId)_mix.mp4";
  57. startMixinAudio(videoPath: videoPath, bgmPath: bgmPath, audioPathList: audioPathList, startTimeList: startTimeList, outPath: outPath, result: result)
  58. break
  59. case "startMixinPaintedAudio":
  60. let bgmPath = args!["bgmPath"] as! String;
  61. let audioPathList = args!["audioPaths"] as! [String];
  62. let startTimeList = args!["durationList"] as! [Double];
  63. let pathVideoMixinDir = args!["encodePath"] as! String;
  64. startMixinAudio(videoPath: nil, bgmPath: bgmPath, audioPathList: audioPathList, startTimeList: startTimeList, outPath: pathVideoMixinDir, result: result)
  65. break;
  66. case "getIsMediaPlayPause":
  67. result(audioPlayer != nil && audioPlayer!.isPlaying)
  68. break
  69. case "cleanAudioData":
  70. break
  71. case "findIsExistCacheVideo":
  72. result("")
  73. break
  74. case "setExtraFullScreen":
  75. result("")
  76. break
  77. default:
  78. result(FlutterMethodNotImplemented)
  79. }
  80. }
  81. func initAudioSession(){
  82. do {
  83. if (!initFlag) {
  84. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, options: .defaultToSpeaker)
  85. try AVAudioSession.sharedInstance().setActive(true)
  86. initFlag = true
  87. }
  88. } catch {
  89. initFlag = false
  90. }
  91. }
  92. func resultError(code: String, message: String) -> Void {
  93. self.result!(FlutterError(code: code, message: message, details: nil))
  94. }
  95. /// 合成
  96. func startMixinAudio(videoPath: String?, bgmPath: String, audioPathList: [String], startTimeList: [Double], outPath: String, result: @escaping FlutterResult) {
  97. var videoUrl:URL?=nil
  98. if(!(videoPath?.isBlank ?? true)){
  99. videoUrl = URL(fileURLWithPath: videoPath!);
  100. }
  101. let musicUrl = URL(fileURLWithPath: bgmPath)
  102. let composer = DubbingComposer(timeline: startTimeList, videoUrl: videoUrl, musicUrl: musicUrl, recordsUrl: audioPathList)
  103. composer.preTime = preLag
  104. let outputUrl = URL(fileURLWithPath: outPath)
  105. DispatchQueue.global().async {
  106. composer.compose(outputUrl, onSuccess: {
  107. self.result!(outPath)
  108. }) { (message) in
  109. print("合成失败", message)
  110. self.resultError(code: "1005", message: "mix video and audio failed")
  111. }
  112. }
  113. }
  114. }
  115. // MARK: - 录音控制
  116. extension SwiftDubbingLibPlugin {
  117. @objc func startRecord(pathAudio: String, index: Int, duration: Int, fileName: String, result: @escaping FlutterResult) {
  118. initAudioSession()
  119. endPlay()
  120. status = .record
  121. let filePath = pathAudio + fileName + ".aac";
  122. do {
  123. let settings: [String:Any] = [
  124. AVNumberOfChannelsKey : 1, //设置通道
  125. AVFormatIDKey : kAudioFormatMPEG4AAC, //设置录音格式
  126. //AVSampleRateKey : 16000, //设置录音采样率
  127. //AVLinearPCMBitDepthKey : 16, //每个采样点位数,分为8、16、24、32
  128. //AVLinearPCMIsFloatKey : true, //是否使用浮点数采样
  129. ]
  130. let url = URL(fileURLWithPath: filePath)
  131. audioRecorder = try AVAudioRecorder(url: url, settings: settings)
  132. audioRecorder?.prepareToRecord()
  133. audioRecorder?.record()
  134. isRecording = true
  135. } catch {
  136. stopRecord()
  137. resultError(code: "1002", message: "start record failed")
  138. }
  139. if(isRecording){
  140. var piecePosition = 0
  141. let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
  142. let _timer:DispatchSource = DispatchSource.makeTimerSource(flags: [], queue: queue) as! DispatchSource
  143. _timer.schedule(deadline: DispatchTime.now(), repeating: .milliseconds(5))
  144. _timer.setEventHandler(handler: {() -> Void in
  145. self.isRecording = true
  146. piecePosition += 1
  147. self.channel.invokeMethod("recordProgress", arguments: ["progress": piecePosition * 5])
  148. if(piecePosition * 5 >= duration) {
  149. _timer.cancel()
  150. self.result!(filePath)
  151. self.stopRecord()
  152. }
  153. })
  154. _timer.resume()
  155. } else {
  156. resultError(code: "1002", message: "start record failed")
  157. }
  158. }
  159. @objc func playRecord(filePath: String, result: @escaping FlutterResult) {
  160. status = .playRecord
  161. initAudioSession()
  162. do {
  163. let url = URL(fileURLWithPath: filePath)
  164. audioPlayer = try AVAudioPlayer(contentsOf: url)
  165. audioPlayer?.prepareToPlay()
  166. audioPlayer?.volume = 1
  167. audioPlayer?.delegate = self
  168. DispatchQueue.global().async {
  169. self.audioPlayer?.play()
  170. }
  171. } catch {
  172. stopPlayRecord()
  173. }
  174. }
  175. @objc func endPlay() {
  176. switch status {
  177. case .stop:
  178. break
  179. case .record:
  180. stopRecord()
  181. case .playRecord:
  182. stopPlayRecord()
  183. }
  184. }
  185. // 停止录音
  186. @objc func stopRecord() {
  187. status = .stop
  188. audioRecorder?.stop()
  189. audioRecorder = nil
  190. isRecording = false
  191. }
  192. // 停止播放录音
  193. func stopPlayRecord() {
  194. status = .stop
  195. if audioPlayer?.isPlaying == true {
  196. audioPlayer?.stop()
  197. }
  198. audioPlayer = nil
  199. }
  200. }
  201. extension SwiftDubbingLibPlugin: AVAudioPlayerDelegate {
  202. public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  203. stopPlayRecord()
  204. self.result!(flag)
  205. }
  206. public func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
  207. stopPlayRecord()
  208. // self.result!(false)
  209. }
  210. }
  211. extension String{
  212. /// check string cellection is whiteSpace
  213. var isBlank : Bool{
  214. return allSatisfy({$0.isWhitespace})
  215. }
  216. }
  217. extension Optional where Wrapped == String{
  218. var isBlank : Bool{
  219. return self?.isBlank ?? true
  220. }
  221. }