KSAccompanyWebViewController.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  1. //
  2. // KSAccompanyWebViewController.m
  3. // KulexiuForTeacher
  4. //
  5. // Created by Kyle on 2022/3/20.
  6. //
  7. #import "KSAccompanyWebViewController.h"
  8. #import "WebViewBaseConfig.h" // 基础配置
  9. #import "SwiftImportHeader.h" // swift 桥接
  10. #import <KSTunerLibrary/KSTunerLibrary-Swift.h>
  11. #import <KSToolLibrary/KSAudioSessionManager.h> // audio session
  12. #import <KSToolLibrary/KSAQRecordManager.h> // 录音
  13. #import <KSToolLibrary/KSWebSocketManager.h> // web socket
  14. #import <CloudAccompanyLibrary/KSVideoRecordManager.h> // 视频录制
  15. #import <CloudAccompanyLibrary/KSCloudBeatView.h> // 节拍器
  16. #import <KSToolLibrary/MidiPlayerEngine.h> // midi 播放
  17. #import <CloudAccompanyLibrary/kSNewPlayer.h> // mp3 播放器
  18. #import "AccompanyLoadingView.h"
  19. #define KSMidiSongFileKey (@"KSDownloadMidiSong")
  20. // 合成
  21. #import <KSToolLibrary/KSMediaEditor.h>
  22. #import "KSMediaMergeView.h"
  23. @interface KSAccompanyWebViewController ()<KSAQRecordManagerDelegate,KSAudioSessionManagerDelegate,PlayerEngineDelegate,TunerDelegate,kSNewPlayerManagerDelegate>
  24. @property (nonatomic, strong) KSAudioSessionManager *audioSessionManager;
  25. @property (nonatomic, assign) MetronomeType beatType;
  26. @property (nonatomic, strong) MidiPlayerEngine *playerEngine; // player
  27. @property (nonatomic, assign) BOOL initEngineSuccess; // 加载引擎是否成功
  28. @property (nonatomic, assign) float songOriginalSpeed;
  29. @property (nonatomic, assign) float currentSpeed; // 当前播放的速度
  30. @property (nonatomic, assign) BOOL isPlaying; // 是否正在播放的状态
  31. @property (nonatomic, strong) NSString *currentSongId; // song id
  32. @property (nonatomic, strong) NSDictionary *configEngineParm; // 初始化mid播放引擎的参数
  33. @property (nonatomic, strong) NSMutableDictionary *metronomeParm; // 节拍器播放的参数
  34. // 是否发送了musicXML信息
  35. @property (nonatomic, assign) BOOL hasSendStartMessage;
  36. @property (nonatomic, strong) KSAQRecordManager *AQManager;
  37. @property (nonatomic, strong) KSWebSocketManager *socketManager;
  38. @property (nonatomic, strong) NSMutableDictionary *evaluatParm;
  39. // 录制的message
  40. @property (nonatomic, strong) NSMutableDictionary *recordParm;
  41. // 评测开始时发送recordStart消息的标识
  42. @property (nonatomic, assign) BOOL isCompareStart;
  43. // 校音开始时发送 checkStart消息标识
  44. @property (nonatomic, assign) BOOL isSoundCheckStart;
  45. // 自定义UI控件容器
  46. @property (nonatomic, strong) UIView *viewContainer;
  47. @property (nonatomic, strong) KSVideoRecordManager *videoRecordManager;
  48. @property (nonatomic, strong) NSDictionary *endRecordParm;
  49. @property (nonatomic, assign) BOOL isCameraOpen;
  50. @property (nonatomic, strong) AccompanyLoadingView *loadingView;
  51. @property (nonatomic, assign) BOOL isTunerRuning;
  52. @property (nonatomic, strong) Tuner *tuner;
  53. // 延迟校准开始时发送 AdjustStart消息标识
  54. @property (nonatomic, assign) BOOL isDelayCheckStart;
  55. // 检测延迟播放器
  56. @property (nonatomic, strong) kSNewPlayer *dingPlayer;
  57. @property (nonatomic, strong) kSNewPlayer *dongPlayer;
  58. // 音频播放器
  59. @property (nonatomic, strong) kSNewPlayer *musicPlayer;
  60. // 录音开始时间
  61. @property (nonatomic, assign) NSTimeInterval recordStartTime;
  62. // 播放开始时间
  63. @property (nonatomic, assign) NSTimeInterval playerStartTime;
  64. // 播放延迟
  65. @property (nonatomic, assign) NSInteger offsetTime;
  66. @property (nonatomic, assign) BOOL dingPlayerReady;
  67. @property (nonatomic, assign) BOOL dongPlayerReady;
  68. @property (nonatomic, assign) BOOL musicPlayerReady;
  69. @property (nonatomic, strong) NSDictionary *playerParm;
  70. @property (nonatomic, strong) NSMutableArray *delayArray;
  71. @property (nonatomic, assign) NSInteger checkIndex;
  72. @property (nonatomic, assign) NSInteger firstFrequence;
  73. @property (nonatomic, assign) NSInteger secondFrequence;
  74. @property (nonatomic, strong) NSURL *bgAudioUrl;
  75. @property (nonatomic, strong) NSURL *recordUrl;
  76. @property (nonatomic, strong) NSString *accompanyUrl;
  77. @property (nonatomic, assign) BOOL muteAccompany; // 是否静音
  78. @property (nonatomic, assign) NSInteger musicStartTime; // 开始播放的时间
  79. @end
  80. @implementation KSAccompanyWebViewController
  81. - (void)handerAudioInterruption {
  82. if (_playerEngine) {
  83. [self stopPlayAction];
  84. }
  85. if (_musicPlayer) {
  86. [self stopMp3Player];
  87. }
  88. }
  89. - (void)resumeAudioSession {
  90. // 恢复
  91. if (_playerEngine) {
  92. [self.playerEngine resumeAUGraph];
  93. }
  94. }
  95. // 打断处理
  96. - (void)audioInterruption {
  97. if (_videoRecordManager) {
  98. [self.videoRecordManager resetSession];
  99. }
  100. [self handerAudioInterruption];
  101. }
  102. - (void)ignorRecordVideo {
  103. if (_videoRecordManager) {
  104. self.videoRecordManager.skipSaveRecord = YES;
  105. }
  106. }
  107. - (void)stopSession {
  108. if (_videoRecordManager) {
  109. [self.videoRecordManager stopSession];
  110. }
  111. }
  112. - (void)resetPlayerConfig {
  113. [self freeMp3Player]; // 若之前有播放器,剔除
  114. self.firstFrequence = 800;
  115. self.secondFrequence = 800;
  116. self.dingPlayerReady = NO;
  117. self.dongPlayerReady = NO;
  118. self.musicPlayerReady = NO;
  119. self.recordStartTime = 0;
  120. self.playerStartTime = 0;
  121. self.offsetTime = 0;
  122. }
  123. - (void)downloadMp3File:(NSString *)musicUrl {
  124. if (![NSString isEmptyString:musicUrl]) {
  125. NSString *fileName = [musicUrl getUrlFileName];
  126. NSString *filePath = [self getAccompanyFilePathWithName:fileName];
  127. NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:filePath];
  128. if ([self checkSongHasSaveAccompanyWithSongUrl:musicUrl]) {
  129. [self configVideoRecord:fileUrl];
  130. }
  131. else {
  132. MJWeakSelf;
  133. [self downloadUrl:musicUrl success:^{
  134. [weakSelf configVideoRecord:fileUrl];
  135. } faliure:^{
  136. }];
  137. }
  138. }
  139. else {
  140. [self configVideoRecord:nil];
  141. }
  142. }
  143. - (void)initMp3Player:(NSString *)musicUrl checkUrl:(NSString *)checkUrl {
  144. [self resetPlayerConfig];
  145. self.accompanyUrl = musicUrl;
  146. [self.musicPlayer preparePlaySongWithUrl:musicUrl];
  147. [self.dingPlayer preparePlaySongWithUrl:checkUrl];
  148. [self.dongPlayer preparePlaySongWithUrl:checkUrl];
  149. [self prepareMusic];
  150. }
  151. - (void)prepareMusic {
  152. self.dingPlayer.isMute = YES;
  153. [self.dingPlayer startPlayNoSeek];
  154. self.dongPlayer.isMute = YES;
  155. [self.dongPlayer startPlayNoSeek];
  156. self.musicPlayer.isMute = YES;
  157. [self.musicPlayer startPlayNoSeek];
  158. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  159. [self.musicPlayer puasePlay];
  160. self.musicPlayer.isMute = NO;
  161. [self.dingPlayer puasePlay];
  162. self.dingPlayer.isMute = NO;
  163. [self.dongPlayer puasePlay];
  164. self.dongPlayer.isMute = NO;
  165. [self configPlayerDelegate];
  166. });
  167. }
  168. - (void)freeMp3Player {
  169. if (_dingPlayer) {
  170. [self.dingPlayer freePlayer];
  171. }
  172. if (_dongPlayer) {
  173. [self.dongPlayer freePlayer];
  174. }
  175. if (_musicPlayer) {
  176. [self.musicPlayer freePlayer];
  177. }
  178. }
  179. - (void)stopMp3Player {
  180. if (_dingPlayer) {
  181. [self.dingPlayer puasePlay];
  182. }
  183. if (_dongPlayer) {
  184. [self.dongPlayer puasePlay];
  185. }
  186. if (_musicPlayer) {
  187. [self.musicPlayer puasePlay];
  188. }
  189. }
  190. - (void)viewDidLoad {
  191. [super viewDidLoad];
  192. // Do any additional setup after loading the view.
  193. [self configAudioSession];
  194. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:@"appEnterBackground" object:nil];
  195. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground) name:@"appEnterForeground" object:nil];
  196. }
  197. - (void)checkMessage:(id)message {
  198. NSDictionary *result = [message mj_JSONObject];
  199. NSString *type = [[result ks_dictionaryValueForKey:@"header"] ks_stringValueForKey:@"type"];
  200. NSString *commond = [[result ks_dictionaryValueForKey:@"header"] ks_stringValueForKey:@"commond"];
  201. if ([type isEqualToString:@"DELAY_CHECK"] && [commond isEqualToString:@"recordEnd"]) {
  202. NSDictionary *body = [result ks_dictionaryValueForKey:@"body"];
  203. NSTimeInterval micDelay = [body ks_doubleValueForKey:@"firstNoteDelayDuration"] - self.offsetTime;
  204. [self.delayArray addObject:[NSNumber numberWithDouble:micDelay]];
  205. }
  206. }
  207. - (void)connectSocketService {
  208. MJWeakSelf;
  209. self.socketManager.didReceiveMessage = ^(id _Nonnull message) {
  210. dispatch_async(dispatch_get_main_queue(), ^{
  211. [weakSelf checkMessage:message];
  212. // api
  213. NSMutableDictionary *sendMessage = [NSMutableDictionary dictionary];
  214. [sendMessage setValue:@"sendResult" forKey:@"api"];
  215. [sendMessage setValue:message forKey:@"content"];
  216. // 服务返回数据传给H5
  217. [weakSelf postMessage:sendMessage];
  218. });
  219. };
  220. self.socketManager.connectionStatus = ^(BOOL isSuccess) {
  221. dispatch_async(dispatch_get_main_queue(), ^{
  222. if (!isSuccess) {
  223. // NSLog(@"-----连接失败");
  224. if (weakSelf.hasSendStartMessage) {
  225. if (weakSelf.AQManager.isRunning) {
  226. NSDictionary *postParm = @{@"api" : @"cancelEvaluating",
  227. @"content" : @{@"reson":@"服务异常,请重试"}
  228. };
  229. [weakSelf postMessage:postParm];
  230. [weakSelf stopRecordService];
  231. weakSelf.isCompareStart = NO;
  232. weakSelf.isSoundCheckStart = NO;
  233. weakSelf.isDelayCheckStart = NO;
  234. }
  235. }
  236. else if (weakSelf.evaluatParm) {
  237. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:weakSelf.evaluatParm];
  238. NSDictionary *valueDic = [weakSelf.evaluatParm ks_dictionaryValueForKey:@"content"];
  239. [valueDic setValue:@"服务异常,请重试" forKey:@"reson"];
  240. [sendParm setValue:valueDic forKey:@"content"];
  241. [weakSelf postMessage:sendParm];
  242. weakSelf.hasSendStartMessage = YES;
  243. weakSelf.isCompareStart = NO;
  244. weakSelf.isSoundCheckStart = NO;
  245. weakSelf.isDelayCheckStart = NO;
  246. }
  247. else { // 其他断开
  248. if (weakSelf.AQManager.isRunning) {
  249. NSDictionary *postParm = @{@"api" : @"cancelEvaluating",
  250. @"content" : @{@"reson":@"服务异常,请重试"}
  251. };
  252. [weakSelf postMessage:postParm];
  253. [weakSelf stopRecordService];
  254. weakSelf.isCompareStart = NO;
  255. weakSelf.isSoundCheckStart = NO;
  256. weakSelf.isDelayCheckStart = NO;
  257. }
  258. }
  259. }
  260. else {
  261. // NSLog(@"-----连接成功");
  262. if (weakSelf.hasSendStartMessage == NO && weakSelf.evaluatParm) {
  263. NSDictionary *content = [weakSelf.evaluatParm ks_dictionaryValueForKey:@"content"];
  264. NSString *sendData = [weakSelf configDataCommond:@"musicXml" body:content type:@"SOUND_COMPARE"];
  265. [weakSelf sendDataToSocketService:sendData];
  266. [weakSelf postMessage:weakSelf.evaluatParm];
  267. weakSelf.hasSendStartMessage = YES;
  268. }
  269. }
  270. });
  271. };
  272. [self.socketManager SRWebSocketOpen];
  273. }
  274. - (void)appEnterBackground {
  275. NSDictionary *parm = @{@"api":@"suspendPlay"};
  276. [self postMessage:parm];
  277. [self handerAudioInterruption];
  278. }
  279. - (void)appEnterForeground {
  280. if (self.isCameraOpen) {
  281. if ([self.videoRecordManager getSessionStatusisActive] == NO) {
  282. [self.videoRecordManager configSessiondisplayInView:self.viewContainer];
  283. }
  284. }
  285. }
  286. - (void)initWebView {
  287. [self.scrollView removeFromSuperview];
  288. [self.view addSubview:self.viewContainer];
  289. [self.viewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
  290. make.left.right.top.bottom.mas_equalTo(self.view);
  291. }];
  292. if (self.myWebView == nil) {
  293. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  294. config.selectionGranularity = WKSelectionGranularityDynamic;
  295. config.allowsInlineMediaPlayback = YES;
  296. config.mediaTypesRequiringUserActionForPlayback = NO;
  297. config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
  298. config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  299. [self configUserAgent:config];
  300. //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
  301. WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
  302. //这个类主要用来做native与JavaScript的交互管理
  303. WKUserContentController * wkUController = [[WKUserContentController alloc] init];
  304. [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:SCRIPT_NAME];
  305. config.userContentController = wkUController;
  306. WKPreferences *preferences = [WKPreferences new];
  307. // 是否支出javaScript
  308. preferences.javaScriptEnabled = YES;
  309. //不通过用户交互,是否可以打开窗口
  310. preferences.javaScriptCanOpenWindowsAutomatically = YES;
  311. config.preferences = preferences;
  312. self.myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
  313. self.myWebView.opaque = NO;
  314. self.myWebView.UIDelegate = self;
  315. self.myWebView.navigationDelegate = self;
  316. self.myWebView.scrollView.bounces = NO;
  317. self.myWebView.backgroundColor = [UIColor clearColor];
  318. self.myWebView.scrollView.backgroundColor = [UIColor clearColor];
  319. #ifdef DEBUG
  320. if (@available(iOS 16.4, *)) {
  321. self.myWebView.inspectable = YES;
  322. }
  323. #endif
  324. // 加载进度条和title
  325. [self.myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  326. [self.myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
  327. [self.view addSubview:self.myWebView];
  328. [self.myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
  329. make.left.right.mas_equalTo(self.view);
  330. make.top.mas_equalTo(self.view.mas_top);
  331. make.bottom.mas_equalTo(self.view.mas_bottom);
  332. }];
  333. self.myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  334. [self setupProgress];
  335. [self loadRequest];
  336. }
  337. else {
  338. [self.myWebView reload];
  339. }
  340. }
  341. - (void)configUserAgent:(WKWebViewConfiguration *)config {
  342. NSString *oldUserAgent = config.applicationNameForUserAgent;
  343. NSString *newAgent = [NSString stringWithFormat:@"%@ %@ %@",oldUserAgent,AGENT_NAME,AGENT_DOMAIN];
  344. config.applicationNameForUserAgent = newAgent;
  345. }
  346. - (void)configRecordManager {
  347. if (self.AQManager.isRunning) {
  348. [self.AQManager stopRecord];
  349. }
  350. self.AQManager = [[KSAQRecordManager alloc] init];
  351. self.AQManager.delegate = self;
  352. }
  353. - (void)viewWillAppear:(BOOL)animated {
  354. [super viewWillAppear:animated];
  355. [self connectSocketService];
  356. if (self.isCameraOpen) {
  357. [self.videoRecordManager configSessiondisplayInView:self.viewContainer];
  358. }
  359. }
  360. - (void)viewWillDisappear:(BOOL)animated {
  361. [super viewWillDisappear:animated];
  362. if (_socketManager) {
  363. [self.socketManager SRWebSocketClose];
  364. _socketManager = nil;
  365. }
  366. // 停止播放和录制
  367. [self stopSession];
  368. [self stopPlayAction];
  369. [self stopRecordService];
  370. [self stopTuner];
  371. BOOL isBack = [self isViewPopDismiss];
  372. if (isBack) { // 页面销毁才删除
  373. if (_AQManager) {
  374. [_AQManager freeAudioQueue];
  375. _AQManager = nil;
  376. }
  377. // 如果退出评测页面 清除 playerEngine
  378. if (self.playerEngine) {
  379. [self.playerEngine cleanup];
  380. self.playerEngine = nil;
  381. }
  382. // 返回不保存视频
  383. [self ignorRecordVideo];
  384. [self freeMp3Player];
  385. [self removeTuner];
  386. }
  387. }
  388. - (void)removeTuner {
  389. if (_tuner) {
  390. [_tuner freeTuner];
  391. _tuner = nil;
  392. NSLog(@"--- free tuner ");
  393. }
  394. }
  395. - (void)sendDataToSocketService:(id)data {
  396. if (_socketManager) {
  397. [self.socketManager sendData:data];
  398. }
  399. }
  400. #pragma mark --- WKScriptMessageHandler
  401. - (void)userContentController:(WKUserContentController *)userContentController
  402. didReceiveScriptMessage:(WKScriptMessage *)message {
  403. if ([message.name isEqualToString:SCRIPT_NAME]) {
  404. NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
  405. // 回到主线程
  406. dispatch_async(dispatch_get_main_queue(), ^{
  407. if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"createMusicPlayer"]) {
  408. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  409. NSString *musicUrl = [content ks_stringValueForKey:@"musicSrc"];
  410. NSString *checkUrl = [content ks_stringValueForKey:@"tuneSrc"];
  411. self.playerParm = parm;
  412. [self initMp3Player:musicUrl checkUrl:checkUrl];
  413. // 下载文件
  414. [self downloadMp3File:musicUrl];
  415. }
  416. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"startEvaluating"]) { // 开始评测
  417. [self configRecordManager];
  418. self.hasSendStartMessage = NO;
  419. PREMISSIONTYPE isOk = [RecordCheckManager checkMicPermissionAvaiable];
  420. if (isOk == PREMISSIONTYPE_YES) {
  421. self.evaluatParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  422. // 如果socket 连上了
  423. if (self.socketManager.socketReadyState == SR_OPEN) {
  424. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  425. NSString *sendData = [self configDataCommond:@"musicXml" body:content type:@"SOUND_COMPARE"];
  426. [self sendDataToSocketService:sendData];
  427. [self postMessage:parm];
  428. self.hasSendStartMessage = YES;
  429. }
  430. else {
  431. [self connectSocketService];
  432. }
  433. }
  434. else {
  435. NSDictionary *postParm = @{@"api" : @"cancelEvaluating",
  436. @"content" : @{@"reson":@"没有麦克风权限"}
  437. };
  438. [self postMessage:postParm];
  439. }
  440. }
  441. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"endEvaluating"]) {// 停止评测
  442. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  443. self.musicStartTime = 0;
  444. self.evaluatParm = nil;
  445. [self stopRecordService];
  446. [self postMessage:parm];
  447. [self sendEndMessage];
  448. [self stopMp3Player]; // 停止播放
  449. });
  450. }
  451. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cancelEvaluating"]) { // 取消评测
  452. self.musicStartTime = 0;
  453. self.evaluatParm = nil;
  454. [self stopRecordService];
  455. [self postMessage:parm];
  456. [self stopMp3Player]; // 停止播放
  457. }
  458. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"startRecording"]) { // 开始录制
  459. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  460. self.musicStartTime = [content ks_integerValueForKey:@"firstNoteTime"];
  461. if ([[content allKeys] containsObject:@"accompanimentState"]) {
  462. BOOL mute = [content ks_boolValueForKey:@"accompanimentState"] == NO;
  463. self.muteAccompany = mute;
  464. }
  465. else {
  466. self.muteAccompany = NO;
  467. }
  468. if (self->_videoRecordManager) {
  469. [self.videoRecordManager clearVideoFile];
  470. }
  471. [self postMessage:parm];
  472. self.isCompareStart = YES;
  473. [self startRecordService];
  474. }
  475. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"endRecording"]) { // 停止录音
  476. self.recordParm = nil;
  477. [self stopRecordService];
  478. [self postMessage:parm];
  479. }
  480. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"pauseRecording"]) {
  481. [self puaseRecordService];
  482. [self postMessage:parm];
  483. }
  484. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"resumeRecording"]) {
  485. [self resumeRecordService];
  486. [self postMessage:parm];
  487. }
  488. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isWiredHeadsetOn"]) {
  489. [self configAudioDeviceType:parm];
  490. }
  491. // 发送消息给socket service
  492. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"proxyMessage"]) {
  493. [self sendMessageToSocket:parm];
  494. }
  495. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"proxyServiceMessage"]) {
  496. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  497. NSString *sendData = [content mj_JSONString];
  498. NSLog(@"proxyServiceMessage ------- %@",sendData);
  499. [self sendDataToSocketService:sendData];
  500. }
  501. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openCamera"]) { // 开启摄像头
  502. PREMISSIONTYPE canOpenCamera = [RecordCheckManager checkCameraPremissionAvaiable];
  503. PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable];
  504. if (canOpenCamera == PREMISSIONTYPE_YES) {
  505. self.isCameraOpen = YES;
  506. [self.videoRecordManager setIgnoreAudio:YES];
  507. [self.videoRecordManager configSessiondisplayInView:self.viewContainer];
  508. [self postMessage:parm];
  509. }
  510. if (albumEnable == PREMISSIONTYPE_NO) {
  511. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  512. }
  513. }
  514. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"closeCamera"]) { // 关闭摄像头
  515. self.isCameraOpen = NO;
  516. if (self->_videoRecordManager) {
  517. [self.videoRecordManager removeDisplay];
  518. }
  519. [self postMessage:parm];
  520. }
  521. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"startCapture"]) { // 开始录制
  522. PREMISSIONTYPE isOk = [RecordCheckManager checkPhotoLibraryPremissionAvaiable];
  523. if (isOk == PREMISSIONTYPE_YES) {
  524. [self.videoRecordManager setIgnoreAudio:YES];
  525. self.videoRecordManager.audioUrl = self.AQManager.audioUrl;
  526. [self.videoRecordManager startRecord];
  527. [self postMessage:parm];
  528. }
  529. }
  530. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"endCapture"]) { // 结束录制
  531. if (self->_videoRecordManager) {
  532. self.endRecordParm = parm;
  533. [self.videoRecordManager stopRecord];
  534. }
  535. else {
  536. [self postMessage:parm];
  537. }
  538. }
  539. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setCaptureMode"]) {
  540. NSString *modeString = [[parm ks_dictionaryValueForKey:@"content"] ks_stringValueForKey:@"mode"];
  541. BOOL isIgnoreAudio = [modeString isEqualToString:@"evaluating"];
  542. [self postMessage:parm];
  543. [self.videoRecordManager setIgnoreAudio:isIgnoreAudio];
  544. }
  545. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"startSoundCheck"]) { // 开始校音
  546. [self configRecordManager];
  547. [self postMessage:parm];
  548. self.isCompareStart = NO;
  549. self.isSoundCheckStart = YES;
  550. self.isDelayCheckStart = NO;
  551. [self startRecordService];
  552. }
  553. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"endSoundCheck"]) {
  554. // 结束校音
  555. self.isSoundCheckStart = NO;
  556. [self stopRecordService];
  557. [self postMessage:parm];
  558. }
  559. // 音视频合成
  560. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openAdjustRecording"]) {
  561. KSMediaMergeView *mergeView = [[KSMediaMergeView alloc] init];
  562. if (self.bgAudioUrl == nil) {
  563. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"当前曲目无mp3伴奏"];
  564. }
  565. else {
  566. if (self.AQManager && self.AQManager.audioUrl) {
  567. self.recordUrl = self.AQManager.audioUrl;
  568. [self.view addSubview:mergeView];
  569. [mergeView mas_makeConstraints:^(MASConstraintMaker *make) {
  570. make.left.right.top.bottom.mas_equalTo(self.view);
  571. }];
  572. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  573. mergeView.recordId = [content ks_stringValueForKey:@"recordId"];
  574. mergeView.songName = [content ks_stringValueForKey:@"title"];
  575. mergeView.coverImage = [content ks_stringValueForKey:@"coverImg"];
  576. MJWeakSelf;
  577. NSInteger micDelay = [UserDefaultObjectForKey(@"micDelay") integerValue];
  578. NSInteger defaultDelay = self.offsetTime + micDelay;
  579. [mergeView configWithVideoUrl:self.videoRecordManager.videoFileURL bgAudioUrl:self.bgAudioUrl remoteBgUrl:self.accompanyUrl recordUrl:self.recordUrl offsetTime:defaultDelay mergeCallback:^{
  580. [weakSelf musicPublishCallBack:content];
  581. }];
  582. }
  583. else {
  584. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"麦克风被占用"];
  585. }
  586. }
  587. }
  588. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"videoUpdate"]) { // 上传
  589. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  590. NSMutableDictionary *contentParm = [NSMutableDictionary dictionaryWithDictionary:[sendParm ks_dictionaryValueForKey:@"content"]];
  591. if (self.videoRecordManager) {
  592. MJWeakSelf;
  593. [self.videoRecordManager saveVideoCallback:^(BOOL isSuccess, NSString * _Nullable message) {
  594. if (isSuccess) {
  595. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"已保存到相册"];
  596. [weakSelf uploadVideoWithParm:contentParm sendParm:sendParm];
  597. }
  598. }];
  599. }
  600. }
  601. #pragma mark -------- 云教练原生播放对接
  602. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudDetail"]) { // 初始化方法
  603. /**
  604. api: 'cloudDetail',
  605. content: {
  606. midi: '',
  607. denominator: 4,
  608. numerator: 4,
  609. // xml整体原始速度
  610. originalSpeed: 90,
  611. // 间隔(ms)
  612. interval: 50
  613. }
  614. */
  615. [self configAudioSession];
  616. // 重置track num array
  617. self.configEngineParm = [parm copy];
  618. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  619. NSString *midiUrl = [content ks_stringValueForKey:@"midi"];
  620. NSInteger denominator = [content ks_integerValueForKey:@"denominator"];
  621. NSInteger numerator = [content ks_integerValueForKey:@"numerator"];
  622. NSString *beatString = [NSString stringWithFormat:@"%zd/%zd", numerator,denominator];
  623. self.beatType = [self getBeatTypeFromString:beatString];
  624. float originalSpeed = [content ks_floatValueForKey:@"originalSpeed"];
  625. self.songOriginalSpeed = originalSpeed;
  626. self.currentSpeed = originalSpeed;
  627. NSInteger reportInterval = [content ks_integerValueForKey:@"interval"];
  628. // 下载midi文件
  629. BOOL hasSaveSong = [self checkSongHasSaveWithSongUrl:midiUrl];
  630. NSString *fileName = [midiUrl getUrlFileName];
  631. NSString *filePath = [self getFilePathWithName:fileName];
  632. if (hasSaveSong) {
  633. [self configPlayerEngineWithSong:filePath reportTime:reportInterval];
  634. }
  635. else {
  636. MJWeakSelf;
  637. [self downloadMidiFile:midiUrl success:^{
  638. [weakSelf configPlayerEngineWithSong:filePath reportTime:reportInterval];
  639. } faliure:^{
  640. }];
  641. }
  642. }
  643. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudGetMediaStatus"]) { // 获取播放状态
  644. /**
  645. api: 'cloudGetMediaStatus',
  646. content: {
  647. status: 'init' | 'play' | 'suspend'
  648. }
  649. */
  650. NSString *engineStatus = @"init";
  651. if (self.initEngineSuccess) {
  652. if (self.isPlaying) {
  653. engineStatus = @"play";
  654. }
  655. else {
  656. engineStatus = @"suspend";
  657. }
  658. }
  659. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  660. [valueDic setValue:engineStatus forKey:@"status"];
  661. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  662. [sendParm setValue:valueDic forKey:@"content"];
  663. [self postMessage:sendParm];
  664. }
  665. // 播放、暂停、进度、播放结束、跳转指定位置
  666. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudPlay"]) { // 播放
  667. /**
  668. api: 'cloudPlay',
  669. content: {
  670. // 当前曲目id
  671. songID: 0,
  672. // xml整体原始速度
  673. originalSpeed: 90,
  674. // 当前选择速度
  675. speed: 90,
  676. // 开始时间(ms)
  677. startTime: 0
  678. // 播放频率
  679. hertz:440
  680. }
  681. */
  682. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  683. self.currentSongId = [content ks_stringValueForKey:@"songID"];
  684. float speed = [content ks_floatValueForKey:@"speed"];
  685. float originalSpeed = [content ks_floatValueForKey:@"originalSpeed"];
  686. double rate = speed / originalSpeed;
  687. self.currentSpeed = speed;
  688. float hertz = [content ks_floatValueForKey:@"hertz"];
  689. // 播放的hertz
  690. [self.playerEngine adjustPitchByHZ:hertz];
  691. [self.playerEngine setMusicPlayerSpeed:rate];
  692. Float64 startTime = [content ks_doubleValueForKey:@"startTime"];
  693. NSLog(@"------%@", [content ks_stringValueForKey:@"startTime"]);
  694. [self.playerEngine setProgressTime:(startTime/1000)];
  695. // 播放
  696. [self playAction];
  697. [self postMessage:parm];
  698. }
  699. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudSuspend"]) { // 暂停
  700. /**
  701. api: 'cloudSuspend',
  702. content: {
  703. // 当前曲目id
  704. songID: 0,
  705. }
  706. */
  707. [self stopPlayAction];
  708. [self postMessage:parm];
  709. }
  710. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudSetCurrentTime"]) { // // 跳转指定位置
  711. /**
  712. api: 'cloudSetCurrentTime',
  713. content: {
  714. // 当前曲目id
  715. songID: 0,
  716. // 指定位置时间(ms)
  717. currentTime: 0
  718. }
  719. */
  720. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  721. Float64 currentTime = [content ks_doubleValueForKey:@"currentTime"];
  722. if (self.playerEngine) {
  723. [self.playerEngine setProgressTime:(currentTime/1000)];
  724. }
  725. [self postMessage:parm];
  726. }
  727. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudChangeSpeed"]) { // 调速 范围(45-270整数)
  728. /**
  729. api: 'cloudChangeSpeed',
  730. content: {
  731. // 当前曲目id
  732. songID: 0,
  733. // 调整速度
  734. speed: 90
  735. // xml整体原始速度
  736. originalSpeed: 90,
  737. }
  738. */
  739. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  740. float speed = [content ks_floatValueForKey:@"speed"];
  741. float originalSpeed = [content ks_floatValueForKey:@"originalSpeed"];
  742. double rate = speed / originalSpeed;
  743. self.currentSpeed = speed;
  744. [self.playerEngine setMusicPlayerSpeed:rate];
  745. // 回报信息
  746. [self postMessage:parm];
  747. }
  748. // 设置每个轨道音量
  749. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudVolume"]) {
  750. /**
  751. api: 'cloudVolume',
  752. content: {
  753. parts: [
  754. {
  755. name: '',
  756. volume: 90,//0-100
  757. }
  758. ]
  759. }
  760. */
  761. NSLog(@"-cloudVolume -----%@",parm);
  762. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  763. int instrumentId = [content ks_intValueForKey:@"activeMidiId"];
  764. float volume = [content ks_floatValueForKey:@"activeMidiVolume"];
  765. if (instrumentId < 0) {
  766. [self postMessage:parm];
  767. [self.playerEngine getAllTrackVolume];
  768. return;
  769. }
  770. [self.playerEngine volumeTrackVolumeWithInstrumentId:instrumentId volume:volume/100];
  771. [self postMessage:parm];
  772. [self.playerEngine getAllTrackVolume];
  773. }
  774. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudMetronome"]) { // 节拍器播放
  775. self.metronomeParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  776. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  777. NSInteger repeatCount = [content ks_integerValueForKey:@"repeat"];
  778. NSInteger denominator = [content ks_integerValueForKey:@"denominator"];
  779. NSInteger numerator = [content ks_integerValueForKey:@"numerator"];
  780. NSInteger supplement = [content ks_integerValueForKey:@"supplement"];
  781. NSString *beatString = [NSString stringWithFormat:@"%zd/%zd", numerator,denominator];
  782. self.beatType = [self getBeatTypeFromString:beatString];
  783. [self showBeatViewRepeatCount:repeatCount supplement:supplement];
  784. }
  785. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudDestroy"]) { // 销毁播放器
  786. self.initEngineSuccess = NO;
  787. // 重置track num array
  788. self.isPlaying = NO;
  789. if (self.playerEngine) {
  790. [self.playerEngine cleanup];
  791. self.playerEngine = nil;
  792. }
  793. }
  794. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudLoading"]) { // loading
  795. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  796. BOOL showLoading = [content ks_boolValueForKey:@"show"];
  797. if (showLoading) {
  798. [self showCustomLoading];
  799. }
  800. else {
  801. [self removeCustomLoadingView];
  802. }
  803. }
  804. // 跟音
  805. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudToggleFollow"]) {
  806. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  807. NSString *status = [content ks_stringValueForKey:@"state"];
  808. if ([status isEqualToString:@"start"]) { // 开始
  809. [self startTuner];
  810. }
  811. else if ([status isEqualToString:@"end"]) { // 结束
  812. [self stopTuner];
  813. }
  814. }
  815. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cloudAccompanyMessage"]) { // 获取伴奏 废弃⚠️
  816. }
  817. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"startTune"]) { // 延迟测试开始
  818. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  819. NSInteger count = [content ks_integerValueForKey:@"count"];
  820. if (count == 0) {
  821. [self.delayArray removeAllObjects];
  822. self.checkIndex = 0;
  823. }
  824. self.checkIndex += 1;
  825. [self configRecordManager];
  826. [self postMessage:parm];
  827. self.isCompareStart = NO;
  828. self.isSoundCheckStart = NO;
  829. self.isDelayCheckStart = YES;
  830. [self startRecordService];
  831. }
  832. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"endTune"]) { // 延迟测试停止
  833. self.isDelayCheckStart = NO;
  834. [self stopRecordService];
  835. [self postMessage:parm];
  836. [self stopMp3Player];
  837. [self sendAdjustEndMessage]; // 发送结束消息
  838. }
  839. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"finishTune"]) { // 延迟测试结束
  840. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  841. NSInteger errorCount = 0;
  842. NSInteger totalDelay = 0;
  843. for (NSInteger index = 0 ; index < self.delayArray.count; index++) {
  844. NSInteger micDelay = [self.delayArray[index] integerValue];
  845. if (micDelay > 10 && micDelay < 100) {
  846. totalDelay += micDelay;
  847. }
  848. else {
  849. errorCount++;
  850. }
  851. }
  852. NSMutableDictionary *contentParm = [NSMutableDictionary dictionaryWithDictionary:content];
  853. if (errorCount > 1) { // 错误次数过多
  854. [contentParm setValue:@(NO) forKey:@"result"];
  855. }
  856. else {
  857. [contentParm setValue:@(YES) forKey:@"result"];
  858. NSInteger averageDelay = totalDelay / (self.delayArray.count - errorCount);
  859. UserDefaultSet([NSNumber numberWithDouble:averageDelay], @"micDelay");
  860. }
  861. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  862. [sendParm setValue:@"finishTune" forKey:@"api"];
  863. [sendParm setValue:contentParm forKey:@"content"];
  864. [self postMessage:sendParm];
  865. [self.delayArray removeAllObjects];
  866. self.checkIndex = 0;
  867. }
  868. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getDeviceDelay"]) {
  869. NSInteger micDelay = [UserDefaultObjectForKey(@"micDelay") integerValue];
  870. NSMutableDictionary *content = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  871. [content setValue:[NSNumber numberWithInteger:micDelay] forKey:@"value"];
  872. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  873. [sendParm setValue:@"getDeviceDelay" forKey:@"api"];
  874. [sendParm setValue:content forKey:@"content"];
  875. [self postMessage:sendParm];
  876. }
  877. else {
  878. [super handleScriptMessageSource:parm];
  879. }
  880. });
  881. }
  882. }
  883. - (void)musicPublishCallBack:(NSDictionary *)content {
  884. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  885. [parm setValue:@"hideComplexButton" forKey:@"api"];
  886. [parm setValue:@{} forKey:@"content"];
  887. [self postMessage:parm];
  888. }
  889. - (void)uploadVideoWithParm:(NSMutableDictionary *)contentParm sendParm:(NSMutableDictionary *)sendParm {
  890. // MJWeakSelf;
  891. // [self.videoRecordManager uploadRecordVideoSuccess:^(NSString * _Nonnull videoUrl) {
  892. // [contentParm setValue:@"success" forKey:@"type"];
  893. // [contentParm setValue:videoUrl forKey:@"filePath"];
  894. // [contentParm setValue:@"上传成功" forKey:@"message"];
  895. // [sendParm setValue:contentParm forKey:@"content"];
  896. //
  897. // [weakSelf postMessage:sendParm];
  898. // } failure:^(NSString * _Nonnull desc) {
  899. // [contentParm setValue:@"error" forKey:@"type"];
  900. // [contentParm setValue:desc forKey:@"message"];
  901. // [sendParm setValue:contentParm forKey:@"content"];
  902. // [weakSelf postMessage:sendParm];
  903. // }];
  904. }
  905. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  906. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  907. } confirm:^{
  908. [self openSettingView];
  909. }];
  910. }
  911. - (void)openSettingView {
  912. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  913. }
  914. - (void)downloadUrl:(NSString *)url success:(void(^)(void))success faliure:(void(^)(void))faliure {
  915. [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
  916. } success:^(NSURL * _Nonnull fileUrl) {
  917. if ([self saveAccompanyFileWithUrl:fileUrl accompanyUrl:url]) {
  918. if (success) {
  919. success();
  920. }
  921. }
  922. } faliure:^(NSError * _Nonnull error) {
  923. if (faliure) {
  924. faliure();
  925. }
  926. }];
  927. }
  928. - (void)configVideoRecord:(NSURL *)path {
  929. self.videoRecordManager.bgAudioUrl = path;
  930. self.bgAudioUrl = path;
  931. }
  932. - (void)showBeatViewRepeatCount:(NSInteger)repeatCount supplement:(NSInteger)supplement {
  933. KSCloudBeatView *beatView = [KSCloudBeatView shareInstanceWithBeatType:self.beatType speed:self.currentSpeed repeatCount:repeatCount supplement:supplement];
  934. MJWeakSelf;
  935. [beatView startPlayWithEndCallback:^(BOOL isCancle) {
  936. if (isCancle) { // 取消
  937. [weakSelf sendEndMetronomeMessage:YES];
  938. }
  939. else { // 播放完成
  940. [weakSelf sendEndMetronomeMessage:NO];
  941. }
  942. }];
  943. [self.view addSubview:beatView];
  944. }
  945. - (void)sendEndMetronomeMessage:(BOOL)isCancel {
  946. NSString *status = isCancel ? @"cancel" : @"finish";
  947. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[self.metronomeParm ks_dictionaryValueForKey:@"content"]];
  948. [valueDic setValue:status forKey:@"status"];
  949. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:self.metronomeParm];
  950. [sendParm setValue:valueDic forKey:@"content"];
  951. [self postMessage:sendParm];
  952. }
  953. - (void)downloadMidiFile:(NSString *)midiUrl success:(void(^)(void))success faliure:(void(^)(void))faliure {
  954. [KSNetworkingManager downloadFileRequestWithFileUrl:midiUrl progress:^(int64_t bytesRead, int64_t totalBytes) {
  955. } success:^(NSURL * _Nonnull fileUrl) {
  956. if ([self saveMidiFileWithUrl:fileUrl midiUrl:midiUrl]) {
  957. if (success) {
  958. success();
  959. }
  960. }
  961. } faliure:^(NSError * _Nonnull error) {
  962. if (faliure) {
  963. faliure();
  964. }
  965. }];
  966. }
  967. - (BOOL)saveMidiFileWithUrl:(NSURL *)fileUrl midiUrl:(NSString *)midiUrl {
  968. NSData *sourceData = [NSData dataWithContentsOfURL:fileUrl];
  969. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  970. NSString *filePath= [cachePath stringByAppendingPathComponent:@"MidiSong"];
  971. // 先创建子目录
  972. NSFileManager *fileManager = [NSFileManager defaultManager];
  973. if (![fileManager fileExistsAtPath:filePath]) {
  974. [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
  975. }else{
  976. NSLog(@"已创建文件夹");
  977. }
  978. NSString *fileName = [midiUrl getUrlFileName];
  979. NSString *tempPath = [filePath stringByAppendingPathComponent:fileName];
  980. BOOL success = [sourceData writeToFile:tempPath atomically:NO];
  981. return success;
  982. }
  983. - (NSString *)getFilePathWithName:(NSString *)fileName {
  984. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  985. NSString *filePath= [cachePath stringByAppendingPathComponent:@"MidiSong"];
  986. return [filePath stringByAppendingPathComponent:fileName];;
  987. }
  988. - (BOOL)checkSongHasSaveWithSongUrl:(NSString *)songUrl {
  989. BOOL hasSaveFile = NO;
  990. NSString *fileName = [songUrl getUrlFileName];
  991. NSString *filePath = [self getFilePathWithName:fileName];
  992. NSFileManager *fileManager = [NSFileManager defaultManager];
  993. if ([fileManager fileExistsAtPath:filePath]) {
  994. hasSaveFile = YES;
  995. }
  996. return hasSaveFile;
  997. }
  998. - (void)sendMessageToSocket:(NSDictionary *)parm {
  999. NSString *messageHeader = @"proxyMessage";
  1000. NSString *sendMessage = [self configDataCommond:messageHeader body:[parm ks_dictionaryValueForKey:@"content"]];
  1001. [self sendDataToSocketService:sendMessage];
  1002. }
  1003. - (void)configAudioDeviceType:(NSDictionary *)parm {
  1004. AUDIODEVICE_TYPE type = [KSAQRecordManager queryAudioOutputDeviceType];
  1005. NSString *valueStr = @"";
  1006. BOOL checkIsWired = NO;
  1007. switch (type) {
  1008. case AUDIODEVICE_TYPE_HEADPHONE:
  1009. {
  1010. valueStr = @"有线耳机";
  1011. checkIsWired = YES;
  1012. }
  1013. break;
  1014. case AUDIODEVICE_TYPE_BLUETOOTH:
  1015. {
  1016. valueStr = @"蓝牙耳机";
  1017. checkIsWired = YES;
  1018. }
  1019. break;
  1020. case AUDIODEVICE_TYPE_NONE:
  1021. {
  1022. valueStr = @"";
  1023. checkIsWired = NO;
  1024. }
  1025. break;
  1026. default:
  1027. break;
  1028. }
  1029. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  1030. [valueDic setValue:valueStr forKey:@"type"];
  1031. [valueDic setValue:[NSNumber numberWithBool:checkIsWired] forKey:@"checkIsWired"];
  1032. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  1033. [sendParm setValue:valueDic forKey:@"content"];
  1034. [self postMessage:sendParm];
  1035. }
  1036. - (void)startRecordService {
  1037. if (self.AQManager.isRunning) {
  1038. [self.AQManager stopRecord];
  1039. }
  1040. [self.AQManager startRecord];
  1041. }
  1042. - (void)stopRecordService {
  1043. if (self.AQManager.isRunning) {
  1044. [self.AQManager stopRecord];
  1045. }
  1046. }
  1047. - (void)puaseRecordService {
  1048. if (self.AQManager.isRunning) {
  1049. [self.AQManager pauserRecord];
  1050. }
  1051. }
  1052. - (void)resumeRecordService {
  1053. [self.AQManager resumeRecord];
  1054. }
  1055. - (void)sendEndMessage {
  1056. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1057. // 上传停止的信息 发送给服务端
  1058. NSString *endMessage = @"recordEnd";
  1059. NSString *endData = [self configDataCommond:endMessage body:nil type:@"SOUND_COMPARE"];
  1060. [self sendDataToSocketService:endData];
  1061. self.isCompareStart = NO;
  1062. NSLog(@"---- send end message");
  1063. });
  1064. }
  1065. - (void)sendAdjustEndMessage {
  1066. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1067. // 上传停止的信息 发送给服务端
  1068. NSString *endMessage = @"recordEnd";
  1069. NSString *endData = [self configDataCommond:endMessage body:nil type:@"DELAY_CHECK"];
  1070. [self sendDataToSocketService:endData];
  1071. self.isDelayCheckStart = NO;
  1072. NSLog(@"---- send adjust end message");
  1073. });
  1074. }
  1075. - (void)sendOffsetTimeToService {
  1076. // 上传停止的信息 发送给服务端
  1077. NSString *offsetMessage = @"audioPlayStart";
  1078. NSTimeInterval micDelay = [UserDefault(@"micDelay") doubleValue];
  1079. NSDictionary *dic = @{@"offsetTime" : [NSNumber numberWithInteger:self.offsetTime], @"micDelay": [NSNumber numberWithInteger:micDelay]};
  1080. NSString *endData = [self configDataCommond:offsetMessage body:dic type:@"SOUND_COMPARE"];
  1081. NSLog(@"------ %@", endData);
  1082. [self sendDataToSocketService:endData];
  1083. self.isCompareStart = NO;
  1084. }
  1085. #pragma mark-------- KSAQRecordManagerDelegate
  1086. - (void)recordInterruption {
  1087. NSDictionary *postParm = @{@"api" : @"cancelEvaluating",
  1088. @"content" : @{@"reson":@"录制错误,请重试"}
  1089. };
  1090. [self postMessage:postParm];
  1091. }
  1092. - (void)audioRouteChange:(AUDIODEVICE_TYPE)type {
  1093. NSString *valueStr = @"";
  1094. BOOL checkIsWired = NO;
  1095. switch (type) {
  1096. case AUDIODEVICE_TYPE_HEADPHONE:
  1097. {
  1098. valueStr = @"有线耳机";
  1099. checkIsWired = YES;
  1100. }
  1101. break;
  1102. case AUDIODEVICE_TYPE_BLUETOOTH:
  1103. {
  1104. valueStr = @"蓝牙耳机";
  1105. checkIsWired = YES;
  1106. }
  1107. break;
  1108. case AUDIODEVICE_TYPE_NONE:
  1109. {
  1110. valueStr = @"";
  1111. checkIsWired = NO;
  1112. }
  1113. break;
  1114. default:
  1115. break;
  1116. }
  1117. NSDictionary *postParm = @{@"api" : @"listenerWiredStatus",
  1118. @"content" : @{@"type":valueStr,
  1119. @"checkIsWired":[NSNumber numberWithBool:checkIsWired]
  1120. }
  1121. };
  1122. [self postMessage:postParm];
  1123. }
  1124. #pragma mark ------- 评测app播放
  1125. - (void)recordDidStart:(NSTimeInterval)time { // ms
  1126. self.recordStartTime = time;
  1127. if (self.isDelayCheckStart) {
  1128. NSLog(@"---- delay - record did start %f", time);
  1129. // 播放音频
  1130. // 播放校音音频
  1131. dispatch_main_sync_safe(^{
  1132. if (self.checkIndex % 2 == 0) {
  1133. [self.dongPlayer startPlay];
  1134. }
  1135. else {
  1136. [self.dingPlayer startPlay];
  1137. }
  1138. });
  1139. }
  1140. else if (self.isCompareStart) {
  1141. NSLog(@"---- compare - record did start %f", time);
  1142. // 播放伴奏
  1143. dispatch_main_sync_safe(^{
  1144. self.musicPlayer.isMute = self.muteAccompany;
  1145. [self.musicPlayer seekToTimePlay:self.musicStartTime];
  1146. });
  1147. }
  1148. }
  1149. - (void)audioRecord:(KSAQRecordManager *)audioRecord didRecordAudioData:(void *)data length:(UInt32)length {
  1150. if (self.socketManager.socketReadyState != SR_OPEN) {
  1151. return;
  1152. }
  1153. NSData *pushData = [[NSData alloc] initWithBytes:data length:length];
  1154. if (self.isCompareStart) { // 发送评测开始消息
  1155. dispatch_async(dispatch_get_main_queue(), ^{
  1156. NSDate *date = [NSDate date];
  1157. NSTimeInterval inteveral = [date timeIntervalSince1970];
  1158. double beginTime = inteveral - audioRecord.sampleTime;
  1159. NSDictionary *parm = @{
  1160. @"api" : @"recordStartTime",
  1161. @"content" : @{@"inteveral" : [NSNumber numberWithDouble:beginTime]}
  1162. };
  1163. [self postMessage:parm];
  1164. });
  1165. NSLog(@"--------- send start message");
  1166. _isCompareStart = NO;
  1167. NSString *startMessage = @"recordStart";
  1168. NSString *startString = [self configDataCommond:startMessage body:nil type:@"SOUND_COMPARE"];
  1169. [self sendDataToSocketService:startString];
  1170. }
  1171. else if (self.isSoundCheckStart) { // 校音开始
  1172. NSLog(@"--------- send check start message");
  1173. _isSoundCheckStart = NO;
  1174. NSString *checkStartMessage = @"start";
  1175. NSString *startString = [self configDataCommond:checkStartMessage body:nil type:@"PITCH_DETECTION"];
  1176. [self sendDataToSocketService:startString];
  1177. }
  1178. else if (self.isDelayCheckStart) {
  1179. NSLog(@"--------- send delay check start message");
  1180. _isDelayCheckStart = NO;
  1181. NSString *checkStartMessage = @"recordStart";
  1182. NSInteger frequence = 0.0f;
  1183. if (self.checkIndex % 2 == 0) {
  1184. frequence = self.secondFrequence;
  1185. }
  1186. else {
  1187. frequence = self.firstFrequence;
  1188. }
  1189. NSDictionary *parm = @{@"HZ" : @(frequence)};
  1190. NSString *startString = [self configDataCommond:checkStartMessage body:parm type:@"DELAY_CHECK"];
  1191. [self sendDataToSocketService:startString];
  1192. }
  1193. // NSLog(@"--------- send audio data length %d", length);
  1194. [self sendDataToSocketService:pushData];
  1195. }
  1196. - (NSString *)configDataCommond:(NSString *)commond body:(id)bodyMessage type:(NSString *)dataType {
  1197. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  1198. if (bodyMessage) {
  1199. [parm setValue:bodyMessage forKey:@"body"];
  1200. }
  1201. NSMutableDictionary *headerParm = [NSMutableDictionary dictionary];
  1202. if ([NSString isEmptyString:commond]) {
  1203. [headerParm setValue:@"" forKey:@"commond"];
  1204. }
  1205. else {
  1206. [headerParm setValue:commond forKey:@"commond"];
  1207. }
  1208. if (![NSString isEmptyString:dataType]) {
  1209. [headerParm setValue:dataType forKey:@"type"];
  1210. }
  1211. [headerParm setValue:@(200) forKey:@"status"];
  1212. [parm setValue:headerParm forKey:@"header"];
  1213. return [parm mj_JSONString];
  1214. }
  1215. - (NSString *)configDataCommond:(NSString *)commond body:(id)bodyMessage {
  1216. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  1217. if (bodyMessage) {
  1218. [parm setValue:bodyMessage forKey:@"body"];
  1219. }
  1220. if ([NSString isEmptyString:commond]) {
  1221. [parm setValue:@{@"commond":@""} forKey:@"header"];
  1222. }
  1223. else {
  1224. [parm setValue:@{@"commond":commond} forKey:@"header"];
  1225. }
  1226. return [parm mj_JSONString];
  1227. }
  1228. - (KSWebSocketManager *)socketManager {
  1229. if (!_socketManager) {
  1230. _socketManager = [[KSWebSocketManager alloc] initWithUrl:SOCKET_URL userId:UserDefault(UIDKey) tokenType:UserDefault(TokenKey) token:UserDefault(TokenKey)];
  1231. }
  1232. return _socketManager;
  1233. }
  1234. #pragma mark --- lazying
  1235. - (UIView *)viewContainer {
  1236. if (!_viewContainer) {
  1237. _viewContainer = [[UIView alloc] init];
  1238. }
  1239. return _viewContainer;
  1240. }
  1241. - (KSVideoRecordManager *)videoRecordManager {
  1242. if (!_videoRecordManager) {
  1243. MJWeakSelf;
  1244. _videoRecordManager = [[KSVideoRecordManager alloc] initSessionRecordCallback:^(BOOL isSuccess, NSString * _Nullable message) {
  1245. if (isSuccess) {
  1246. [weakSelf showSuccessMessage:message];
  1247. }
  1248. else {
  1249. if (![NSString isEmptyString:message]) {
  1250. [LOADING_MANAGER MBShowAUTOHidingInWindow:message];
  1251. }
  1252. }
  1253. }];
  1254. }
  1255. return _videoRecordManager;
  1256. }
  1257. - (void)showSuccessMessage:(NSString *)message {
  1258. if (![NSString isEmptyString:message]) {
  1259. [LOADING_MANAGER MBShowAUTOHidingInWindow:message];
  1260. }
  1261. // 成功
  1262. if (self.endRecordParm) {
  1263. [self postMessage:self.endRecordParm];
  1264. self.endRecordParm = nil;
  1265. }
  1266. }
  1267. - (MetronomeType)getBeatTypeFromString:(NSString *)typeString {
  1268. if ([typeString isEqualToString:@"1/4"]) {
  1269. return MetronomeType1V4;
  1270. }
  1271. else if ([typeString isEqualToString:@"2/4"]) {
  1272. return MetronomeType2V4;
  1273. }
  1274. else if ([typeString isEqualToString:@"3/4"]) {
  1275. return MetronomeType3V4;
  1276. }
  1277. else if ([typeString isEqualToString:@"4/4"]) {
  1278. return MetronomeType4V4;
  1279. }
  1280. else if ([typeString isEqualToString:@"3/8"]) {
  1281. return MetronomeType3V8;
  1282. }
  1283. else if ([typeString isEqualToString:@"6/8"]) {
  1284. return MetronomeType6V8;
  1285. }
  1286. else {
  1287. return MetronomeType4V4;
  1288. }
  1289. }
  1290. #pragma mark ------- midi 播放相关
  1291. - (void)configPlayerEngineWithSong:(NSString *)songPath reportTime:(NSInteger)reportTime {
  1292. self.initEngineSuccess = NO;
  1293. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1294. self.playerEngine = [[MidiPlayerEngine alloc] init];
  1295. self.playerEngine.reportTime = reportTime;
  1296. self.playerEngine.delegate = self;
  1297. [self.playerEngine configSoundFilePath:[[NSBundle mainBundle]
  1298. pathForResource:@"synthgms" ofType:@"sf2"]];
  1299. [self.playerEngine loadMIDIFileWithString:songPath];
  1300. });
  1301. }
  1302. - (void)configAudioSession {
  1303. self.audioSessionManager = [[KSAudioSessionManager alloc] init];
  1304. self.audioSessionManager.delegate = self;
  1305. [self.audioSessionManager configAudioSession:AUDIOCONFIG_PLAYANDRECORD];
  1306. }
  1307. #pragma mark ---- PlayerEngineDelegate
  1308. /** 进度更新
  1309. api: 'cloudTimeUpdae',
  1310. content: {
  1311. // 当前曲目id
  1312. songID: 0,
  1313. // 当前位置时间(ms)
  1314. currentTime: 0
  1315. }
  1316. */
  1317. /** 播放结束事件
  1318. api: 'cloudplayed',
  1319. content: {
  1320. // 当前曲目id
  1321. songID: 0,
  1322. }
  1323. */
  1324. - (void)ProgressUpdated:(float)progress currentPlayTime:(MusicTimeStamp)currentPlayTime currentTime:(NSTimeInterval)currentTime {
  1325. if (self.isPlaying == NO) {
  1326. return;
  1327. }
  1328. // 回调
  1329. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  1330. [sendParm setValue:@"cloudTimeUpdae" forKey:@"api"];
  1331. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1332. [content setValue:self.currentSongId forKey:@"songID"];
  1333. [content setValue:@(currentPlayTime*1000) forKey:@"currentTime"];
  1334. [sendParm setValue:content forKey:@"content"];
  1335. [self postMessage:sendParm];
  1336. }
  1337. - (void)playEnd {
  1338. [self stopPlayAction];
  1339. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  1340. [sendParm setValue:@"cloudplayed" forKey:@"api"];
  1341. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1342. [content setValue:self.currentSongId forKey:@"songID"];
  1343. [sendParm setValue:content forKey:@"content"];
  1344. [self postMessage:sendParm];
  1345. }
  1346. - (void)initPlayerEngineSuccess:(float)totalTime {
  1347. self.initEngineSuccess = YES;
  1348. if (self.configEngineParm) {
  1349. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:self.configEngineParm];
  1350. NSMutableDictionary *content = [NSMutableDictionary dictionaryWithDictionary:[sendParm ks_dictionaryValueForKey:@"content"]];
  1351. [content setValue:@(totalTime*1000) forKey:@"midiDuration"];
  1352. [sendParm setValue:content forKey:@"content"];
  1353. [self postMessage:sendParm];
  1354. self.configEngineParm = nil;
  1355. }
  1356. }
  1357. // 总时长
  1358. - (void)GetMusicTotalTime:(float)time {
  1359. }
  1360. #pragma mark ----- 播放控制
  1361. - (void)playAction {
  1362. if (self.playerEngine) {
  1363. self.isPlaying = YES;
  1364. [self.playerEngine playMIDIFile];
  1365. }
  1366. }
  1367. - (void)stopPlayAction {
  1368. if (self.playerEngine) {
  1369. self.isPlaying = NO;
  1370. if ([self.playerEngine isPlayingFile]) {
  1371. [self.playerEngine stopPlayingMIDIFile];
  1372. }
  1373. }
  1374. }
  1375. #pragma mark ----- 小酷AI loading
  1376. - (AccompanyLoadingView *)loadingView {
  1377. if (!_loadingView) {
  1378. _loadingView = [AccompanyLoadingView shareInstance];
  1379. MJWeakSelf;
  1380. [_loadingView loadingCallback:^{
  1381. [weakSelf backAction];
  1382. }];
  1383. }
  1384. return _loadingView;
  1385. }
  1386. - (void)showCustomLoading {
  1387. if ([self.view.subviews containsObject:self.loadingView]) {
  1388. return;
  1389. }
  1390. [self.view addSubview:self.loadingView];
  1391. [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
  1392. make.left.top.right.bottom.mas_equalTo(self.view);
  1393. }];
  1394. [self.view bringSubviewToFront:self.loadingView];
  1395. [self.loadingView showLoading];
  1396. }
  1397. - (void)removeCustomLoadingView {
  1398. [self.loadingView stopLoading];
  1399. }
  1400. #pragma mark ----- 跟音模块
  1401. - (void)startTuner {
  1402. if (self.isTunerRuning == NO) {
  1403. self.isTunerRuning = YES;
  1404. [self.tuner start];
  1405. }
  1406. }
  1407. - (void)stopTuner {
  1408. if (self.isTunerRuning) {
  1409. self.isTunerRuning = NO;
  1410. [self.tuner stop];
  1411. }
  1412. }
  1413. - (Tuner *)tuner {
  1414. if (!_tuner) {
  1415. _tuner = [[Tuner alloc] initWithThreshold:0 smoothing:0.25];
  1416. _tuner.delegate = self;
  1417. }
  1418. return _tuner;
  1419. }
  1420. - (void)tunerDidUpdate:(Tuner *)tuner output:(TunerOutput *)output {
  1421. if (output.amplitude < 0.01) {
  1422. }
  1423. else {
  1424. // 回调频率
  1425. NSDictionary *parm = @{
  1426. @"api" : @"cloudFollowTime",
  1427. @"content" : @{@"frequency" : [NSNumber numberWithDouble:output.frequency]}
  1428. };
  1429. [self postMessage:parm];
  1430. }
  1431. NSLog(@"-------- %@%zd --- distance :%f frequence : %f" , output.pitch, output.octave, output.distance, output.frequency);
  1432. }
  1433. #pragma mark ---- 保存伴奏
  1434. - (BOOL)saveAccompanyFileWithUrl:(NSURL *)fileUrl accompanyUrl:(NSString *)accompanyUrl {
  1435. NSData *sourceData = [NSData dataWithContentsOfURL:fileUrl];
  1436. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  1437. NSString *filePath= [cachePath stringByAppendingPathComponent:@"AccompanySong"];
  1438. // 先创建子目录
  1439. NSFileManager *fileManager = [NSFileManager defaultManager];
  1440. if (![fileManager fileExistsAtPath:filePath]) {
  1441. [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
  1442. }else{
  1443. NSLog(@"已创建文件夹");
  1444. }
  1445. NSString *fileName = [accompanyUrl getUrlFileName];
  1446. NSString *tempPath = [filePath stringByAppendingPathComponent:fileName];
  1447. BOOL success = [sourceData writeToFile:tempPath atomically:NO];
  1448. return success;
  1449. }
  1450. - (NSString *)getAccompanyFilePathWithName:(NSString *)fileName {
  1451. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  1452. NSString *filePath= [cachePath stringByAppendingPathComponent:@"AccompanySong"];
  1453. return [filePath stringByAppendingPathComponent:fileName];;
  1454. }
  1455. - (BOOL)checkSongHasSaveAccompanyWithSongUrl:(NSString *)songUrl {
  1456. BOOL hasSaveFile = NO;
  1457. NSString *fileName = [songUrl getUrlFileName];
  1458. NSString *filePath = [self getAccompanyFilePathWithName:fileName];
  1459. NSFileManager *fileManager = [NSFileManager defaultManager];
  1460. if ([fileManager fileExistsAtPath:filePath]) {
  1461. hasSaveFile = YES;
  1462. }
  1463. return hasSaveFile;
  1464. }
  1465. #pragma mark ---- player
  1466. - (void)configPlayerDelegate {
  1467. self.dingPlayer.delegate = self;
  1468. self.dongPlayer.delegate = self;
  1469. self.musicPlayer.delegate = self;
  1470. }
  1471. - (kSNewPlayer *)dingPlayer {
  1472. if (!_dingPlayer) {
  1473. _dingPlayer = [[kSNewPlayer alloc] init];
  1474. }
  1475. return _dingPlayer;
  1476. }
  1477. - (kSNewPlayer *)dongPlayer {
  1478. if (!_dongPlayer) {
  1479. _dongPlayer = [[kSNewPlayer alloc] init];
  1480. }
  1481. return _dongPlayer;
  1482. }
  1483. - (kSNewPlayer *)musicPlayer {
  1484. if (!_musicPlayer) {
  1485. _musicPlayer = [[kSNewPlayer alloc] init];
  1486. }
  1487. return _musicPlayer;
  1488. }
  1489. #pragma mark ---- new player delegate
  1490. - (void)getSongCurrentTime:(NSInteger)currentTime andTotalTime:(NSInteger)totalTime andProgress:(CGFloat)progress currentInterval:(NSTimeInterval)currentInterval playTime:(NSTimeInterval)playTime inPlayer:(kSNewPlayer *)player {
  1491. if (player == self.dingPlayer || player == self.dongPlayer) {
  1492. if (playTime >= 300 && playTime < 310 && self.recordStartTime > 0) {
  1493. NSLog(@" --- check player start play time %f", currentInterval*1000 - playTime);
  1494. self.playerStartTime = currentInterval*1000 - playTime;
  1495. self.offsetTime = self.playerStartTime - self.recordStartTime;
  1496. NSLog(@"--------- check player offset time -- %zd", self.offsetTime);
  1497. }
  1498. }
  1499. if (playTime >= self.musicStartTime + 300 && playTime < self.musicStartTime + 310 && player == self.musicPlayer) {
  1500. if (self.recordStartTime > 0) {
  1501. NSInteger newPlayTime = playTime - self.musicStartTime; // 选段
  1502. NSLog(@" --- music player start play time %f", currentInterval*1000 - newPlayTime);
  1503. self.playerStartTime = currentInterval*1000 - newPlayTime;
  1504. self.offsetTime = self.playerStartTime - self.recordStartTime;
  1505. NSLog(@"--------- music play offset time -- %zd", self.offsetTime);
  1506. [self sendOffsetTimeToService];
  1507. }
  1508. NSLog(@"------- record start time %f", self.recordStartTime);
  1509. }
  1510. // 回调进度
  1511. if (player == self.musicPlayer) {
  1512. // NSLog(@"------ music play progress - %f", progress);
  1513. // 回调进度
  1514. NSDictionary *parm = @{
  1515. @"api" : @"playProgress",
  1516. @"content" : @{@"currentTime" : [NSNumber numberWithInteger:currentTime],
  1517. @"totalDuration" : [NSNumber numberWithInteger:totalTime],
  1518. }
  1519. };
  1520. // NSLog(@" -----music play progress %@---- ", parm);
  1521. [self postMessage:parm];
  1522. }
  1523. }
  1524. - (void)sendPlayerReadyMsg {
  1525. if (self.playerParm) {
  1526. [self postMessage:self.playerParm];
  1527. }
  1528. }
  1529. - (void)playerIsReadyPlay:(kSNewPlayer *)player {
  1530. if (player == self.musicPlayer) {
  1531. self.musicPlayerReady = YES;
  1532. }
  1533. else if (player == self.dingPlayer) {
  1534. self.dingPlayerReady = YES;
  1535. }
  1536. else if (player == self.dongPlayer) {
  1537. self.dongPlayerReady = YES;
  1538. }
  1539. // 如果都准备好
  1540. if (self.musicPlayerReady && self.dingPlayerReady && self.dongPlayerReady) {
  1541. [self sendPlayerReadyMsg];
  1542. }
  1543. }
  1544. - (void)playerDidError:(kSNewPlayer *)player {
  1545. [self stopRecordService];
  1546. [self stopMp3Player]; // 停止播放
  1547. // 播放出现问题
  1548. NSDictionary *postParm = @{@"api" : @"cancelEvaluating",
  1549. @"content" : @{@"reson":@"播放已停止"}
  1550. };
  1551. [self postMessage:postParm];
  1552. }
  1553. - (NSMutableArray *)delayArray {
  1554. if (!_delayArray) {
  1555. _delayArray = [NSMutableArray array];
  1556. }
  1557. return _delayArray;
  1558. }
  1559. /*
  1560. #pragma mark - Navigation
  1561. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1562. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1563. // Get the new view controller using [segue destinationViewController].
  1564. // Pass the selected object to the new view controller.
  1565. }
  1566. */
  1567. @end