state.ts 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. import { closeToast, showToast } from "vant";
  2. import { nextTick, reactive, watch } from "vue";
  3. import { OpenSheetMusicDisplay } from "../osmd-extended/src";
  4. import { metronomeData } from "./helpers/metronome";
  5. import { GradualNote, GradualTimes, GradualVersion } from "./type";
  6. import { handleEndEvaluat, handleStartEvaluat } from "./view/evaluating";
  7. import { IFingering, mappingVoicePart, subjectFingering, matchVoicePart } from "/src/view/fingering/fingering-config";
  8. import { handleStartTick, closeTick } from "./view/tick";
  9. import { audioListStart, getAudioCurrentTime, getAudioDuration, setAudioCurrentTime, setAudioPlaybackRate, audioData } from "./view/audio-list";
  10. import { toggleFollow } from "./view/follow-practice";
  11. import { browser, setStorageSpeed, setGlobalData } from "./utils";
  12. import { api_cloudGetMediaStatus, api_createMusicPlayer, api_cloudChangeSpeed, api_cloudSuspend, api_cloudSetCurrentTime, api_cloudDestroy } from "./helpers/communication";
  13. import { verifyCanRepeat, getDuration } from "./helpers/formateMusic";
  14. import { getMusicSheetDetail } from "./utils/baseApi"
  15. import { getQuery } from "/src/utils/queryString";
  16. import { followData, skipNotePractice } from "/src/view/follow-practice/index"
  17. import { changeSongSourceByBate } from "/src/view/audio-list"
  18. import { moveSmoothAnimation, smoothAnimationState, moveSmoothAnimationByPlayTime, moveTranslateXNum, destroySmoothAnimation, calcClientWidth } from "/src/page-instrument/view-detail/smoothAnimation"
  19. import { storeData } from "/src/store";
  20. import { downloadXmlStr } from "./view/music-score"
  21. import { musicScoreRef } from "/src/page-instrument/view-detail/index"
  22. import { headTopData } from "/src/page-instrument/header-top/index";
  23. const query: any = getQuery();
  24. /** 入门 | 进阶 | 大师 */
  25. export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
  26. /** 渲染类型: 五线谱,简谱 */
  27. export enum EnumMusicRenderType {
  28. /** 五线谱 */
  29. staff = "staff",
  30. /** 简谱(首调) */
  31. firstTone = "firstTone",
  32. /** 固定音高 */
  33. fixedTone = "fixedTone",
  34. }
  35. export const musicscoresettingKey = "musicscoresetting";
  36. /** 有声音的是那个音源 */
  37. export type IPlayState = "music" | "background" | "mingSong";
  38. /** 播放状态 */
  39. export type IAudioState = "play" | "paused";
  40. /** 来源 */
  41. export enum IPlatform {
  42. APP = "APP",
  43. PC = "PC",
  44. }
  45. export type ISonges = {
  46. background?: string
  47. music?: string
  48. }
  49. /**
  50. * 特殊教材分类id
  51. */
  52. const classids = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 30, 31, 35, 36, 38, 108, 150, 151, 152, 153, 154, 155, 156, 157, 158, 178, 179, 180, 181, 182]; // 大雅金唐, 竖笛教程, 声部训练展开的分类ID
  53. // 乐器code码
  54. export const musicalInstrumentCodeInfo = [
  55. {
  56. name: '长笛',
  57. code: 'Flute',
  58. id: 1
  59. },
  60. {
  61. name: '短笛',
  62. code: 'Piccolo',
  63. id: 2
  64. },
  65. {
  66. name: '单簧管',
  67. code: 'Clarinet',
  68. id: 3
  69. },
  70. {
  71. name: '低音单簧管',
  72. code: 'Bass Clarinet',
  73. id: 4
  74. },
  75. {
  76. name: '中音萨克斯',
  77. code: 'Alto Saxophone',
  78. id: 5
  79. },
  80. {
  81. name: '次中音萨克斯',
  82. code: 'Tenor Saxophone',
  83. id: 6
  84. },
  85. {
  86. name: '高音萨克斯',
  87. code: 'Soprano Saxophone',
  88. id: 7
  89. },
  90. {
  91. name: '上低音萨克斯',
  92. code: 'Baritone Saxophone',
  93. id: 8
  94. },
  95. {
  96. name: '双簧管',
  97. code: 'Oboe',
  98. id: 9
  99. },
  100. {
  101. name: '大管',
  102. code: 'Bassoon',
  103. id: 10
  104. },
  105. {
  106. name: '小号',
  107. code: 'Trumpet',
  108. id: 11
  109. },
  110. {
  111. name: '圆号',
  112. code: 'Horn',
  113. id: 12
  114. },
  115. {
  116. name: '长号',
  117. code: 'Trombone',
  118. id: 13
  119. },
  120. {
  121. name: '上低音号',
  122. code: 'Baritone',
  123. id: 14
  124. },
  125. {
  126. name: '次中音号',
  127. code: 'Euphonium',
  128. id: 15
  129. },
  130. {
  131. name: '大号',
  132. code: 'Tuba',
  133. id: 16
  134. },
  135. {
  136. name: '钢琴',
  137. code: 'Piano',
  138. id: 17
  139. },
  140. {
  141. name: '电钢琴',
  142. code: 'Electronical Piano',
  143. id: 18
  144. },
  145. {
  146. name: '钢片琴',
  147. code: 'Glockenspiel',
  148. id: 19
  149. },
  150. {
  151. name: '小提琴',
  152. code: 'Violin',
  153. id: 20
  154. },
  155. {
  156. name: '中提琴',
  157. code: 'Viola',
  158. id: 21
  159. },
  160. {
  161. name: '大提琴',
  162. code: 'Violoncello',
  163. id: 22
  164. },
  165. {
  166. name: '低音提琴',
  167. code: 'Contrabass',
  168. id: 23
  169. },
  170. {
  171. name: '架子鼓',
  172. code: 'Drum Set',
  173. id: 24
  174. },
  175. {
  176. name: '小鼓',
  177. code: 'Snare Drum',
  178. id: 25
  179. },
  180. {
  181. name: '马林巴',
  182. code: 'Marimba',
  183. id: 26
  184. },
  185. {
  186. name: '颤音琴',
  187. code: 'Vibraphone',
  188. id: 27
  189. },
  190. {
  191. name: '钟琴',
  192. code: 'Chimes',
  193. id: 28
  194. },
  195. {
  196. name: '木琴',
  197. code: 'Xylophone',
  198. id: 29
  199. },
  200. {
  201. name: '管钟',
  202. code: 'Tubular Bells',
  203. id: 30
  204. },
  205. {
  206. name: '定音鼓',
  207. code: 'Timpani',
  208. id: 31
  209. },
  210. {
  211. name: '键盘',
  212. code: 'Mallets',
  213. id: 32
  214. },
  215. {
  216. name: '排箫',
  217. code: 'Panpipes',
  218. id: 33
  219. },
  220. {
  221. name: '陶笛',
  222. code: 'Ocarina',
  223. id: 34
  224. },
  225. {
  226. name: '陶笛',
  227. code: 'Alto Ocarina',
  228. id: 34
  229. },
  230. {
  231. name: '葫芦丝',
  232. code: 'Woodwind',
  233. id: 35
  234. },
  235. {
  236. name: '葫芦丝',
  237. code: 'Hulusi',
  238. id: 35
  239. },
  240. {
  241. name: '口风琴',
  242. code: 'Nai',
  243. id: 36
  244. },
  245. {
  246. name: '口风琴',
  247. code: 'Melodica',
  248. id: 36
  249. },
  250. {
  251. name: '德式竖笛',
  252. code: 'Tenor Recorder',
  253. id: 37
  254. },
  255. {
  256. name: '德式竖笛',
  257. code: 'German Recorder',
  258. id: 37
  259. },
  260. {
  261. name: '英式竖笛',
  262. code: 'Baroque Recorder',
  263. id: 38
  264. },
  265. {
  266. name: '高音陶笛',
  267. code: 'Whistling',
  268. id: 39
  269. },
  270. {
  271. name: '高音陶笛',
  272. code: 'Soprano Ocarina',
  273. id: 39
  274. },
  275. ]
  276. const state = reactive({
  277. /** 来源 : PC , app */
  278. platform: "" as IPlatform,
  279. appName: "" as "GYM" | "COLEXIU",
  280. musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
  281. /**曲谱是否渲染完成 */
  282. musicRendered: false,
  283. /** 当前曲谱数据ID, 和曲谱ID不一致 */
  284. detailId: "",
  285. /** 曲谱资源URL */
  286. xmlUrl: "",
  287. /** 声部ID */
  288. subjectId: 0 as number,
  289. trackId: 0 as string | number,
  290. isVip: false, // 是否会员
  291. /** 分类ID */
  292. categoriesId: 0,
  293. /** 分类名称 */
  294. categoriesName: "",
  295. /** 是否支持评测 */
  296. enableEvaluation: true,
  297. /** 是否支持转谱 */
  298. enableNotation: false,
  299. /** 后台设置不能转谱,但是默认谱面不是五线谱时,需要显示转谱按钮,此时只能转首调和固定调 */
  300. specialShowNotation: false,
  301. /** 曲谱ID */
  302. examSongId: "",
  303. /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
  304. cbsExamSongId: "",
  305. /** 曲谱名称 */
  306. examSongName: "",
  307. /** 曲谱封面 */
  308. coverImg: "",
  309. /** 扩展字段 */
  310. extConfigJson: {} as any,
  311. /** 扩展样式字段 */
  312. extStyleConfigJson: {} as any,
  313. /** 是否开启节拍器(mp3节拍器) */
  314. isOpenMetronome: false,
  315. /** 演唱模式是否开启节拍器(mp3节拍器) */
  316. isSingOpenMetronome: false,
  317. /** 是否显示指法 */
  318. isShowFingering: false,
  319. /** 原音 */
  320. music: "",
  321. /** 伴奏 */
  322. accompany: "",
  323. /** 范唱 */
  324. fanSong: "",
  325. /** 伴唱 */
  326. banSong: "",
  327. /** 唱名 */
  328. mingSong: "",
  329. /** 节拍器音乐资源 */
  330. beatSong: {
  331. music: "",
  332. accompany: "",
  333. fanSong: "",
  334. banSong: "",
  335. mingSong: ""
  336. },
  337. /** midiURL */
  338. midiUrl: "",
  339. /** 父分ID */
  340. parentCategoriesId: 0,
  341. /** 分类ID */
  342. musicSheetCategoriesId: 0,
  343. /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
  344. bizMusicCategoryId: 0,
  345. /** 资源类型: mp3 | midi */
  346. playMode: "MP3" as "MP3" | "MIDI",
  347. /** 设置的速度 */
  348. speed: 0,
  349. /** 曲谱音频正常的速度 */
  350. originSpeed: 0,
  351. /** 播放过程中显示的速度 */
  352. playIngSpeed: 0,
  353. /** 分轨名称 */
  354. track: "",
  355. /** 当前显示声部索引 */
  356. partIndex: 0,
  357. /** 演奏是否需要节拍器 */
  358. needTick: false,
  359. /** 演唱模式是否需要节拍器 */
  360. needSingTick: false,
  361. /** 曲谱实例 */
  362. osmd: null as unknown as OpenSheetMusicDisplay,
  363. /**是否是特殊乐谱类型, 主要针对管乐迷 */
  364. isSpecialBookCategory: false,
  365. /** 播放状态 */
  366. playState: "paused" as IAudioState,
  367. /** 播放结束状态 */
  368. playEnd: false,
  369. /** 播放类型 演奏 演唱 */
  370. playType: "play" as "play" | "sing",
  371. /** 播放那个: 原音,伴奏 */
  372. playSource: "music" as IPlayState,
  373. /** 播放进度 */
  374. playProgress: 0,
  375. /** 激活的note index */
  376. activeNoteIndex: 0,
  377. /** 激活的小节 */
  378. activeMeasureIndex: -1,
  379. /** 选段状态 */
  380. sectionStatus: false,
  381. /** 选段数据 */
  382. section: [] as any[],
  383. /** 选段背景 */
  384. sectionBoundingBoxs: [] as any[],
  385. /** 开启选段预备 */
  386. isOpenPrepare: false,
  387. /** 选段预备 */
  388. sectionFirst: null as any,
  389. /** 音符数据 */
  390. times: [] as any[],
  391. /** 播放模式 */
  392. modeType: "practise" as "practise" | "follow" | "evaluating",
  393. /** 设置 */
  394. setting: {
  395. /** 效音提醒 */
  396. soundEffect: true,
  397. /** 护眼模式 */
  398. eyeProtection: false,
  399. /** 摄像头 */
  400. camera: false,
  401. /** 摄像头透明度 */
  402. cameraOpacity: 70,
  403. /** 循环播放 */
  404. repeatAutoPlay: true,
  405. /** 显示指法 */
  406. displayFingering: true,
  407. /** 显示光标 */
  408. displayCursor: true,
  409. /** 频率 */
  410. frequency: 0,
  411. /** 评测难度 */
  412. evaluationDifficulty: "BEGINNER" as IDifficulty,
  413. /** 保存到相册 */
  414. saveToAlbum: true,
  415. /** 开启伴奏 */
  416. enableAccompaniment: true,
  417. /** 反应时间 */
  418. reactionTimeMs: 0,
  419. /** 节拍器音量 */
  420. beatVolume: 50
  421. },
  422. /** 后台设置的基准评测频率 */
  423. baseFrequency: 440,
  424. /** mp3节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
  425. fixtime: 0,
  426. /** evxml等待播放的时间 */
  427. evXmlBeginTime: 0,
  428. /** 第二遍循环evxml等待播放的时间 */
  429. secondEvXmlBeginTime: 0,
  430. /** evxml等待播放的时间集合,多遍反复播放,会有多个timegap(前奏)时间 */
  431. evXmlBeginArr: [] as any,
  432. /** 指法信息 */
  433. fingeringInfo: {} as IFingering,
  434. /** 滚动容器的ID */
  435. scrollContainer: "musicAndSelection",
  436. /** 是否是打击乐 */
  437. isPercussion: false,
  438. /** 评测标准 */
  439. evaluationStandard: '',
  440. /** 是否重复节拍器的时间 */
  441. repeatedBeats: 0,
  442. /**当前曲谱中所有声部名字 */
  443. partListNames: [] as any,
  444. /** 渐变速度信息 */
  445. gradual: [] as GradualNote[],
  446. /** 渐变速度版本 */
  447. gradualVersion: GradualVersion.BASE as GradualVersion,
  448. /** 渐变时间信息 */
  449. gradualTimes: null as GradualTimes,
  450. /** 单声部多声轨 */
  451. multitrack: 0,
  452. /** 缩放 */
  453. zoom: 0.8,
  454. /** 渲染曲谱比例 */
  455. musicZoom: 1,
  456. /** 练习,评测是否是选段模式 */
  457. isSelectMeasureMode: false,
  458. /** 是否是评分显示 */
  459. isReport: false,
  460. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  461. isHideEvaluatReportSaveBtn: false,
  462. /** 是否是合奏 */
  463. isConcert: false,
  464. /** 用户选择的结束小节数 */
  465. userChooseEndIndex: 0,
  466. /** 重播小节集合信息 */
  467. repeatInfo: [] as any,
  468. /** 多分轨的曲子,可支持筛选的分轨 */
  469. canSelectTracks: [] as any,
  470. /** 声部codeId */
  471. subjectCodeId: 0 as number,
  472. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  473. musicalCodeId: 0 as number,
  474. /** 乐器code,用于评测传参 */
  475. musicalCode: '' as any,
  476. /** 合奏曲目是否合并展示 */
  477. isCombineRender: false,
  478. /** 小节的持续时长,以后台设置的播放速度计算 */
  479. measureTime: 0,
  480. /** 跟练模式,节拍器播放的时间 */
  481. beatStartTime: 0,
  482. /** 是否为详情预览模式 */
  483. isPreView: false,
  484. /** 是否为评测报告模式 */
  485. isEvaluatReport: false,
  486. /** midi播放器是否初始化中 */
  487. midiPlayIniting: false,
  488. /** 曲目信息 */
  489. songs: {} as ISonges,
  490. isAppPlay: false, // 是否midi音频,midi是app播放
  491. /** 音频播放器实例 */
  492. audiosInstance: null as any,
  493. /** midi音频的时长 */
  494. durationNum: 0,
  495. midiSectionStart: 0,
  496. /** 音频文件是否加载完成 */
  497. audioDone: false,
  498. /** 是否为单行谱渲染模式 */
  499. isSingleLine: true,
  500. /** 是否是evxml */
  501. isEvxml: false,
  502. noTimes: [] as any,
  503. /** 老师端:功能按钮布局方向 */
  504. playBtnDirection: "left" as "left" | "right",
  505. /** 云练习按钮方向,如果有指法并且是竖向的指法,为了防止播放按钮把指法挡住,此时云练习播放按钮方向应该取反 */
  506. musicScoreBtnDirection: "right" as "left" | "right",
  507. /** 是否在老师端上课页面 */
  508. isAttendClass: false,
  509. /** 引导页信息 */
  510. guideInfo: null as any,
  511. noteCoords: [] as any,
  512. specialPosInit: false,
  513. /** 资源类型 */
  514. paymentType: null,
  515. /** 播放模式,默认练习模式 */
  516. defaultModeType: 1,
  517. /** 音符最多歌词次数 */
  518. maxLyricNum: 0,
  519. /** 小节dom集合 */
  520. vfmeasures: [] as SVGAElement[],
  521. /** 作曲家 */
  522. musicComposer: '',
  523. /** 作词家 */
  524. musicLyricist: '',
  525. // 加载条
  526. isLoading: true,
  527. /** 加载中的文案 */
  528. loadingText: '音频资源加载中,请稍后…',
  529. /** 是否是简单的单行谱模式页面 */
  530. isSimplePage: false,
  531. /** xml的速度和后台设置的速度,计算出的基础音频播放倍率 */
  532. originAudioPlayRate: 1,
  533. /** 开始播放时,记录的mp3播放倍率,用户当前设置的速度/当前小节的速度 */
  534. basePlayRate: 1,
  535. /** 引导页显示状态 */
  536. hasDriverPop: false,
  537. /** 播放倍率不等于1,或者是选段评测,APP暂时不支持保存演奏,需要给出提示 */
  538. noSavePopShow: true,
  539. /** xml里面是否有歌词 */
  540. xmlHasLyric: false,
  541. /** 生成图片的模式 */
  542. isCreateImg: false,
  543. /** 切换谱面后,作业选段是否需要刷新 */
  544. workSectionNeedReset: false,
  545. });
  546. const browserInfo = browser();
  547. let offset_duration = 0;
  548. /** 自定义数据 */
  549. export const customData = reactive({
  550. /** 自定义音符时值 */
  551. customNoteRealValue: [] as any,
  552. /** 自定义音符按读取到的时值 */
  553. customNoteCurrentTime: false,
  554. });
  555. /** 在渲染前后计算光标应该走到的音符 */
  556. export const setStep = () => {
  557. // console.log('播放状态',state.playState)
  558. if (state.playState !== "play") {
  559. console.log("暂停播放");
  560. return;
  561. }
  562. let startTime = Date.now();
  563. requestAnimationFrame(() => {
  564. const endTime = Date.now();
  565. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  566. if (endTime - startTime < 16.7) {
  567. handlePlaying();
  568. setStep();
  569. } else {
  570. setTimeout(() => {
  571. handlePlaying();
  572. setStep();
  573. }, 16.7);
  574. }
  575. });
  576. };
  577. /** 开始播放 */
  578. export const onPlay = () => {
  579. console.log("开始播放", '音频总时长:', getAudioDuration());
  580. state.playEnd = false;
  581. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  582. offset_duration = 0.2;
  583. setStep();
  584. };
  585. /** 播放模式结束自动重播 */
  586. const autoResetPlay = () => {
  587. if (state.modeType !== "practise") return;
  588. skipNotePlay(0, true);
  589. // 没有开启自动重播, 不是练习模式
  590. if (!state.setting.repeatAutoPlay) return;
  591. scrollViewNote();
  592. setTimeout(() => {
  593. togglePlay("play");
  594. }, 1000);
  595. };
  596. /** 播放完成事件 */
  597. export const onEnded = () => {
  598. console.log("音频播放结束");
  599. // if (state.isAppPlay) {
  600. // // 销毁播放器
  601. // api_cloudDestroy();
  602. // }
  603. if (state.playEnd) {
  604. console.log('音频播放结束,无需再次执行')
  605. return
  606. }
  607. // 修改状态为结束
  608. state.playEnd = true;
  609. state.playState = "paused";
  610. // 结束播放
  611. audioListStart(state.playState);
  612. // 调用结束评测
  613. handleEndEvaluat(true);
  614. // 调用自动重复播放
  615. autoResetPlay();
  616. };
  617. // 根据当前小节动态设置,右上角展示的速度
  618. const dynamicShowPlaySpeed = (index: number) => {
  619. const item: any = state.times[index];
  620. if (item && item.measureSpeed ) {
  621. // console.log('速度1',item.measureSpeed)
  622. state.speed = Math.floor(state.basePlayRate * item.measureSpeed)
  623. }
  624. }
  625. // 开始播放时,计算mp3的播放倍率
  626. export const initSetPlayRate = () => {
  627. const item: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
  628. if (item && item.measureSpeed) {
  629. const ratio = state.speed / item.measureSpeed
  630. // state.audiosInstance?.setSpeed(ratio)
  631. state.basePlayRate = ratio || 1;
  632. console.log('播放倍率',state.basePlayRate)
  633. }
  634. }
  635. // 重置播放倍率
  636. export const resetBaseRate = (idx?: number) => {
  637. const index = idx ? idx : 0;
  638. const currentItem: any = state.times[index];
  639. const currentSpeed = currentItem?.measureSpeed ? currentItem.measureSpeed : state.originSpeed;
  640. // console.log('速度2',currentSpeed)
  641. state.speed = currentSpeed
  642. //state.activeNoteIndex = 0
  643. state.basePlayRate = 1;
  644. }
  645. /**
  646. * 播放一直触发的事件
  647. */
  648. const handlePlaying = () => {
  649. const currentTime = getAudioCurrentTime();
  650. const duration = getAudioDuration();
  651. state.playProgress = (currentTime / duration) * 100;
  652. let item = getNote(currentTime);
  653. if (item) {
  654. // 选段状态下
  655. if (state.sectionStatus && state.section.length === 2) {
  656. // 如果开启了预备拍
  657. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  658. const selectEndItem = state.section[1];
  659. /**
  660. * #9374,反复小节的曲目播放错误, bug修复
  661. * 曲目:噢!苏珊娜-排箫-人音
  662. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  663. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  664. */
  665. if (state.repeatInfo.length) {
  666. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  667. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  668. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  669. const preItem = state.times[item.i - 1]
  670. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  671. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  672. if (skipItem) {
  673. // 跳转到指定的音频位置
  674. setAudioCurrentTime(skipItem.time, skipItem.i);
  675. gotoNext(skipItem);
  676. return
  677. }
  678. }
  679. }
  680. }
  681. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  682. // if (currentTime - selectEndItem.endtime > offset_duration) {
  683. //console.log(currentTime,selectEndItem.endtime)
  684. if (currentTime - selectEndItem.endtime >= 0) {
  685. console.log("选段播放结束", state.setting.repeatAutoPlay);
  686. // 如果为选段评测模式
  687. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  688. onEnded();
  689. return;
  690. }
  691. // #8698 bug修复
  692. if (state.modeType === "practise" && state.sectionStatus) {
  693. onEnded();
  694. // state.activeNoteIndex = state.sectionFirst ? state.sectionFirst.i : state.section[0].i
  695. // dynamicShowPlaySpeed(state.activeNoteIndex)
  696. resetPlaybackToStart();
  697. return;
  698. }
  699. item = selectStartItem;
  700. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  701. }
  702. }
  703. gotoNext(item);
  704. dynamicShowPlaySpeed(item.i);
  705. }
  706. // 评测不播放叮咚节拍器
  707. // if (state.modeType !== "evaluating") {
  708. // metronomeData.metro?.sound(currentTime);
  709. // }
  710. metronomeData.metro?.sound(currentTime);
  711. // 一行谱,需要滚动小节
  712. if (state.isSingleLine) {
  713. moveSmoothAnimationByPlayTime()
  714. }
  715. };
  716. /** 跳转到指定音符开始播放 */
  717. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  718. const item = state.times[itemIndex];
  719. let itemTime = item.time;
  720. if (isStart) {
  721. itemTime = 0;
  722. }
  723. if (item) {
  724. // 非选段模式,点击音符,动态设置右下角的速度
  725. if (item.measureSpeed && state.section.length < 2) {
  726. state.speed = Math.floor(state.basePlayRate * item.measureSpeed)
  727. }
  728. setAudioCurrentTime(itemTime, itemIndex);
  729. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  730. gotoNext(item, true);
  731. metronomeData.metro?.sound(itemTime);
  732. if (state.isAppPlay) {
  733. await api_cloudSetCurrentTime({
  734. currentTime: itemTime * 1000,
  735. songID: state.examSongId,
  736. })
  737. audioData.progress = itemTime
  738. state.midiSectionStart = itemTime
  739. }
  740. // 如果是跟练模式
  741. if (followData.start) {
  742. skipNotePractice()
  743. }
  744. }
  745. };
  746. /**
  747. * 切换曲谱播放状态
  748. * @param playState 需要切换的状态 play:播放, paused: 暂停
  749. */
  750. export const togglePlay = async (playState: "play" | "paused", sourceType?: string) => {
  751. // 如果mp3资源还在加载中,给出提示
  752. if (!state.isAppPlay && !state.audioDone) {
  753. if (sourceType !== 'courseware') showToast('音频资源加载中,请稍后')
  754. return
  755. }
  756. // 播放之前 当为评测模式和不为MIDI时候按 是否禁用节拍器 切换音源
  757. if (playState === 'play' && state.modeType === "practise" && state.playMode !== "MIDI") {
  758. console.log("设置音源")
  759. changeSongSourceByBate(metronomeData.disable)
  760. }
  761. // midi播放
  762. if (state.isAppPlay) {
  763. if (playState === "paused") {
  764. await api_cloudSuspend({
  765. songID: state.examSongId,
  766. })
  767. state.playState = 'paused'
  768. // 当在节拍器播放期间暂停的话 就暂停节拍器
  769. closeTick()
  770. return
  771. }
  772. skipNotePlay(state.activeNoteIndex, false);
  773. await api_cloudChangeSpeed({
  774. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  775. originalSpeed: state.originSpeed,
  776. songID: state.examSongId,
  777. });
  778. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  779. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  780. state.playState = status
  781. } else {
  782. state.playState = playState;
  783. }
  784. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  785. resetPlaybackToStart();
  786. }
  787. // 当在节拍器播放期间暂停的话 就暂停节拍器
  788. if (state.playState === "paused") {
  789. closeTick()
  790. }
  791. // 设置为开始播放时, 如果需要节拍,先播放节拍器 只有在当前播放时间不为0的时候开启节拍器
  792. const isOneMeasureNumberXML = state.section.length === 2 && state.section[0].MeasureNumberXML === 2 //当是选段模式 并且开始小节是第二小节 就不播节拍器(这种情况有预选小节,currentTime是0)
  793. if (state.playState === "play" && getAudioCurrentTime() === 0 && !isOneMeasureNumberXML && ((state.playType === "play" && state.needTick) || (state.playType === "sing" && state.needSingTick))) {
  794. // 如果是系统节拍器 等系统节拍器播完了再播,如果是mp3节拍器 直接播
  795. if ((state.playType === "play" && !state.isOpenMetronome) || (state.playType === "sing" && !state.isSingOpenMetronome)) {
  796. const tickend = await handleStartTick();
  797. // console.log("🚀 ~ tickend:", tickend)
  798. // 节拍器返回false, 取消播放
  799. if (!tickend) {
  800. state.playState = "paused";
  801. return false;
  802. }
  803. } else {
  804. handleStartTick()
  805. }
  806. }
  807. // 如果选段没有结束, 直接开始播放,清空选段状态
  808. if (state.playState == "play") {
  809. if (state.sectionStatus && state.section.length < 2) {
  810. clearSelection();
  811. }
  812. }
  813. initSetPlayRate();
  814. audioListStart(state.playState);
  815. return true;
  816. };
  817. /** 结束播放 */
  818. export const handleStopPlay = () => {
  819. state.playState = "paused";
  820. audioListStart(state.playState);
  821. };
  822. /** 重置播放为开始 */
  823. export const resetPlaybackToStart = () => {
  824. // 如果为选段状态
  825. if (state.sectionStatus && state.section.length === 2) {
  826. state.section = formateSelectMearure(state.section);
  827. return;
  828. } else {
  829. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  830. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  831. }
  832. skipNotePlay(0, true);
  833. };
  834. /** 跳转到指定音符 */
  835. export const gotoCustomNote = (index: number) => {
  836. try {
  837. state.osmd.cursor.reset();
  838. } catch (error) { }
  839. for (let i = 0; i < index; i++) {
  840. state.osmd.cursor.next();
  841. }
  842. };
  843. // 找出离目标元素最近的音符
  844. const computedDistance = (x: number, y: number) => {
  845. let minDistance = -1, minidx = 0;
  846. let a, b, c;
  847. state.noteCoords.forEach((note: any, idx: any) => {
  848. //a,b为直角三角形的两个直角边
  849. a = Math.abs(note.x - x)
  850. b = Math.abs(note.y - y)
  851. //c为直角三角形的斜边
  852. c = Math.sqrt(a * a + b * b) as 0
  853. c = Number(c.toFixed(0)) as 0
  854. if (c !== 0 && (minDistance === - 1 || c < minDistance)) {
  855. //min为元素中离目标元素最近元素的距离
  856. minDistance = c
  857. minidx = idx
  858. }
  859. })
  860. return minidx
  861. };
  862. const customNotePosition = (note: any, cursor: any) => {
  863. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  864. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  865. const pageLeft = document.getElementById('scrollContainer')?.getBoundingClientRect()?.x || 0;
  866. // 元素的位置
  867. const element = document.getElementById('cursorImg-0')?.getBoundingClientRect?.() || { x: 0, y: 0 };
  868. // 找出距离元素最近的音符
  869. if (element.x && element.y) {
  870. const noteIdx = computedDistance(element.x, element.y);
  871. const targetX = state.noteCoords[noteIdx]?.x - pageLeft;
  872. console.log('音符索引', noteIdx)
  873. cursor.cursorElement.style.left = targetX + "px";
  874. cursor.cursorElement.style.transform = `translateX(0px)`;
  875. }
  876. }
  877. }
  878. const setCursorPosition = (note: any, cursor: any, flag?: string) => {
  879. // console.log('音符',note?.i,state.osmd.Cursor.noteGraphicalId,note.svgElement?.attrs?.id)
  880. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  881. /**
  882. * bug:#9920、#9940
  883. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  884. */
  885. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  886. return
  887. }
  888. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  889. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  890. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  891. const cursorLeft = cursor?.cursorElement?.style?.left ? parseFloat(cursor.cursorElement.style.left) : 0;
  892. let patchX = 0;
  893. if (state.cbsExamSongId == '1788502467554750466') {
  894. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  895. patchX = (note.i == 0 || note.i == 60) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i >= 2 || note.i <= 6) || (note.i >= 8 || note.i <= 22) || (note.i >= 24 || note.i <= 37) || (note.i >= 39 || note.i <= 43) || (note.i >= 45 || note.i <= 51) || (note.i >= 53 || note.i <= 57) || (note.i == 59) ? 6 : 0;
  896. }
  897. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  898. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  899. }
  900. } else if (state.cbsExamSongId == '1788501975122489346') {
  901. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  902. patchX = (note.i == 0) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i == 9 || note.i == 10 || note.i == 12 || note.i == 13) ? 3 : (note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59) ? 6 : (note.i == 45) ? -8 : (note.i >= 15 || note.i <= 29) || (note.i >= 31 || note.i <= 36) || (note.i >= 38 || note.i <= 44) || (note.i >= 46 || note.i <= 50) || (note.i >= 52 || note.i <= 58) || (note.i >= 60 || note.i <= 64) || (note.i == 66) ? 4 : 0;
  903. }
  904. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  905. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  906. }
  907. }
  908. if (flag === 'refresh' || (flag === 'init' && !state.specialPosInit)) {
  909. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  910. cursor.cursorElement.style.left = cursorLeft + patchX + "px";
  911. state.specialPosInit = true;
  912. }
  913. } else {
  914. nextTick(() => {
  915. let bbox = note.bbox;
  916. if (!bbox) {
  917. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  918. x: 0,
  919. y: 0,
  920. };
  921. const parentLeft = musicContainer.x || 0;
  922. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  923. if (noteEle) {
  924. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  925. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  926. if (noteHeadBbox) {
  927. note.bbox = {
  928. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  929. width: noteHeadBbox.width * 1.5,
  930. };
  931. bbox = note.bbox;
  932. }
  933. }
  934. }
  935. if (!bbox) return;
  936. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  937. const width = (bbox.width - baseW) / 3;
  938. // console.log(555555,bbox.left,width)
  939. cursor.cursorElement.style.left = bbox.left + "px";
  940. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  941. });
  942. }
  943. }
  944. };
  945. /**
  946. * 跳转到下一个音符
  947. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  948. **/
  949. export const gotoNext = (note: any, skipNote?: boolean) => {
  950. // console.log(33333333333,state.activeNoteIndex,note.i)
  951. const num = note.i;
  952. if (state.activeNoteIndex === note.i) {
  953. try {
  954. setCursorPosition(note, state.osmd.cursor, 'init');
  955. } catch (error) {
  956. console.log(error);
  957. }
  958. // 重置 或者切换演奏演唱的时候 可能出现 state.activeNoteIndex === note.i的情况 执行
  959. fillWordColor();
  960. if (state.isSingleLine && state.playState === "paused") {
  961. moveSvgDom(skipNote);
  962. }
  963. return;
  964. }
  965. const osmd = state.osmd;
  966. let prev = state.activeNoteIndex;
  967. state.activeNoteIndex = num;
  968. state.activeMeasureIndex = note.MeasureNumberXML;
  969. dynamicShowPlaySpeed(state.activeNoteIndex);
  970. if (prev && num - prev === 1) {
  971. // console.log('跳转音符',11111,osmd.cursor)
  972. // if (!note.id && note.multipleRestMeasures === 0) {
  973. // } else {
  974. // osmd.cursor.next();
  975. // }
  976. osmd.cursor.next();
  977. } else if (prev && num - prev > 0) {
  978. while (num - prev > 0) {
  979. prev++;
  980. // console.log('跳转音符',22222)
  981. osmd.cursor.next();
  982. }
  983. } else {
  984. gotoCustomNote(num);
  985. }
  986. try {
  987. setCursorPosition(note, state.osmd.cursor, 'refresh');
  988. } catch (error) {
  989. console.log(error);
  990. }
  991. fillWordColor();
  992. // 一行谱,需要滚动小节
  993. if (state.isSingleLine) {
  994. moveSvgDom(skipNote);
  995. }
  996. scrollViewNote();
  997. };
  998. /** 获取指定音符 */
  999. export const getNote = (currentTime: number) => {
  1000. const times = state.times;
  1001. const len = state.times.length;
  1002. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  1003. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay && !state.isSimplePage) {
  1004. onEnded();
  1005. return;
  1006. }
  1007. let _item = null as any;
  1008. for (let i = state.activeNoteIndex; i < len; i++) {
  1009. let item = times[i];
  1010. const prevItem = times[i - 1];
  1011. // if (state.isEvxml) {
  1012. // let diffArr: any[] = [];
  1013. // times.forEach((note: any, noteIdx: number) => {
  1014. // if (currentTime >= note.time && currentTime <= times[noteIdx+1].time) {
  1015. // let diffTime = times[noteIdx+1].time - currentTime;
  1016. // diffArr.push({
  1017. // diffTime,
  1018. // idx: noteIdx
  1019. // })
  1020. // }
  1021. // })
  1022. // diffArr.sort((a, b) => a.diffTime - b.diffTime);
  1023. // item = diffArr.length ? times[diffArr[0].idx] : item;
  1024. // }
  1025. if (currentTime >= item.time) {
  1026. if (!prevItem || item.time != prevItem.time) {
  1027. _item = item;
  1028. }
  1029. } else {
  1030. break;
  1031. }
  1032. }
  1033. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  1034. return _item;
  1035. };
  1036. /** 重播 */
  1037. export const handleResetPlay = () => {
  1038. // 如果是midi需要重置播放进度
  1039. if (state.isAppPlay) {
  1040. audioData.progress = 0
  1041. }
  1042. resetBaseRate();
  1043. resetPlaybackToStart();
  1044. // 如果是暂停, 直接播放
  1045. togglePlay("play");
  1046. };
  1047. /** 设置速度 */
  1048. export const handleSetSpeed = (speed: number) => {
  1049. // setStorageSpeed(state.examSongId, speed);
  1050. state.speed = speed;
  1051. // 当前的音符
  1052. const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
  1053. state.basePlayRate = currentItem?.measureSpeed ? state.speed / currentItem.measureSpeed : state.speed / state.originSpeed;
  1054. const actualRate = state.originAudioPlayRate * state.basePlayRate;
  1055. console.log('速度设置',speed,'小节计算的倍率',state.basePlayRate,'实际播放倍率',actualRate)
  1056. };
  1057. /** 清除选段状态 */
  1058. export const clearSelection = () => {
  1059. state.sectionStatus = false;
  1060. state.section = [];
  1061. closeToast();
  1062. };
  1063. /** 开启选段 */
  1064. export const handleChangeSection = () => {
  1065. // 如果开启了选段,再次点击取消选段
  1066. if (state.sectionStatus) {
  1067. togglePlay("paused");
  1068. clearSelection();
  1069. //skipNotePlay(0, true); 取消选段的时候 不跳回开头
  1070. state.sectionFirst = null;
  1071. return;
  1072. }
  1073. state.sectionStatus = true;
  1074. // 开启
  1075. if (state.sectionStatus) {
  1076. togglePlay("paused");
  1077. }
  1078. showToast({
  1079. message: "请选择开始小节",
  1080. duration: 0,
  1081. position: "top",
  1082. className: "selectionToast",
  1083. });
  1084. };
  1085. /** 效验并格式化选段小节 */
  1086. const formateSelectMearure = (_list: any[]): any[] => {
  1087. if (!_list.length) return [];
  1088. const list = _list.sort((a, b) => a.time - b.time);
  1089. const startXml = list[0]?.measureOpenIndex;
  1090. const endXml = list.last()?.measureOpenIndex;
  1091. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  1092. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  1093. // 没有找到选段小节
  1094. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  1095. clearSelection();
  1096. return [];
  1097. }
  1098. list[0] = selectStartMeasure[0];
  1099. list[1] = selectEndMeasure.last();
  1100. let startItemINdex = list[0].i;
  1101. // 开启预备拍
  1102. if (state.isOpenPrepare) {
  1103. const startXmlIndex = list[0].MeasureNumberXML;
  1104. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  1105. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  1106. }
  1107. skipNotePlay(startItemINdex, startItemINdex === 0);
  1108. return list;
  1109. };
  1110. /** 选择选段 */
  1111. export const handleSelection = (item: any) => {
  1112. if (!state.sectionStatus || state.section.length > 1) return;
  1113. if (state.section.length !== 2 && item) {
  1114. state.section.push(item);
  1115. if (state.section.length === 2) {
  1116. setSection(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  1117. //state.section = formateSelectMearure(state.section);
  1118. closeToast();
  1119. }
  1120. }
  1121. if (state.section.length === 1) {
  1122. showToast({
  1123. message: "请选择结束小节",
  1124. duration: 0,
  1125. position: "top",
  1126. className: "selectionToast",
  1127. });
  1128. }
  1129. };
  1130. /** 阶段练习、阶段评测设置选段小节 */
  1131. export const setSection = (start: number, end: number, userSpeed?: number) => {
  1132. const startNotes = state.times.filter(
  1133. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  1134. )
  1135. const endNotes = state.times.filter(
  1136. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  1137. )
  1138. state.userChooseEndIndex = end
  1139. const lastEndId = endNotes[endNotes.length - 1].noteId
  1140. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  1141. // 是否符合重播规则
  1142. const canRepeatInfo = verifyCanRepeat(start, end)
  1143. console.log('能否重播', canRepeatInfo)
  1144. const isCanRepeat = canRepeatInfo.canRepeat
  1145. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1146. /**
  1147. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1148. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  1149. * TODO:通过vf-volta判断是否是跳房子
  1150. */
  1151. let isSkipVolta = false; // 结束小节是否是跳房子小节
  1152. if (lastEndNotes.length === 1) {
  1153. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  1154. }
  1155. let currentEndNum: number = end
  1156. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  1157. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  1158. currentEndNum = currentEndNum - 1
  1159. const newEndNotes = state.times.filter(
  1160. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  1161. )
  1162. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  1163. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  1164. }
  1165. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  1166. const startNote = startNotes[0]
  1167. // const endNote = endNotes[endNotes.length - 1]
  1168. const endNote = lastEndNotes[endIdx]
  1169. if (startNote && endNote) {
  1170. state.isSelectMeasureMode = true;
  1171. // 设置小节
  1172. hanldeDirectSelection([startNote, endNote]);
  1173. // 评测作业,练习作业的场景,需要用老师布置的速度,设置播放速度
  1174. if (userSpeed) {
  1175. handleSetSpeed(userSpeed);
  1176. }
  1177. }
  1178. }
  1179. /** 直接设置选段 */
  1180. export const hanldeDirectSelection = (list: any[]) => {
  1181. if (!Array.isArray(list) || list.length !== 2) return;
  1182. state.sectionStatus = true;
  1183. setTimeout(() => {
  1184. state.section = formateSelectMearure(list);
  1185. // 选段完成后,需要根据预报小节的速度,设置右下角显示的速度
  1186. const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
  1187. if (currentItem.measureSpeed && query.workRecord === undefined) {
  1188. handleSetSpeed(currentItem.measureSpeed);
  1189. }
  1190. console.log('选段小节', state.section)
  1191. }, 0);
  1192. };
  1193. let offsetTop = 0;
  1194. /**
  1195. * 窗口内滚动到音符的区域
  1196. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  1197. * @returns void
  1198. */
  1199. export const scrollViewNote = () => {
  1200. const cursorElement = document.getElementById("cursorImg-0")!;
  1201. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  1202. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  1203. offsetTop = cursorElement.offsetTop;
  1204. if (offsetTop > 50) {
  1205. musicAndSelection.scrollTo({
  1206. top: (offsetTop - 50) * state.musicZoom,
  1207. behavior: "smooth",
  1208. });
  1209. } else {
  1210. musicAndSelection.scrollTo({
  1211. top: 0,
  1212. behavior: "smooth",
  1213. });
  1214. }
  1215. };
  1216. /** 检测是否是节奏练习 */
  1217. export const isRhythmicExercises = () => {
  1218. return state.examSongName.indexOf("节奏练习") > -1;
  1219. };
  1220. /** 重置状态 */
  1221. export const handleRessetState = () => {
  1222. // 切换模式,清除选段
  1223. state.noSavePopShow = true;
  1224. clearSelection();
  1225. skipNotePlay(0, true);
  1226. resetBaseRate();
  1227. // midi 重置播放进度
  1228. if (state.isAppPlay) {
  1229. audioData.progress = 0;
  1230. }
  1231. if (state.modeType === "evaluating") {
  1232. handleStartEvaluat();
  1233. } else if (state.modeType === "practise") {
  1234. togglePlay("paused");
  1235. } else if (state.modeType === "follow") {
  1236. toggleFollow(false);
  1237. }
  1238. };
  1239. export default state;
  1240. /** 初始化评测音频 */
  1241. export const evaluatCreateMusicPlayer = () => {
  1242. return api_createMusicPlayer({
  1243. musicSrc: state.accompany || state.music, // 曲谱音频url
  1244. // tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1245. tuneSrc: "https://oss.dayaedu.com/MECMP/1722593665681.mp3", //效音音频url
  1246. checkFrequence: 496,
  1247. });
  1248. };
  1249. /** 获取内容平台的接口详情并初始化state信息 */
  1250. export const getMusicDetail = async (id: string, type?: string) => {
  1251. const res = await getMusicSheetDetail(id, type);
  1252. if (res?.code === 200) {
  1253. await getMusicInfo(res)
  1254. }
  1255. };
  1256. const getMusicInfo = async (res: any) => {
  1257. const xmlString = await fetch(res.data.xmlFileUrl).then((response) => response.text());
  1258. downloadXmlStr.value = xmlString //给musice-score 赋值xmlString 以免加载2次
  1259. const tracks = xmlToTracks(xmlString) //获取声轨列表
  1260. let index = query["part-index"] ? parseInt(query["part-index"]) : 0
  1261. const musicObj = state.isSimplePage ? {} : initMusicSource(res.data, tracks[index]) //当前part-index找不到声源的时候以第一个为准
  1262. index = tracks.findIndex(item => { // 筛选出当前的index
  1263. return item === musicObj?.track
  1264. })
  1265. const musicInfo = {
  1266. ...res.data,
  1267. track: musicObj?.track
  1268. };
  1269. console.log("🚀 ~ musicInfo:", musicInfo);
  1270. setState(musicInfo, index);
  1271. };
  1272. //获取xml中的音轨数据
  1273. function xmlToTracks(xmlString: string) {
  1274. const xmlParse = new DOMParser().parseFromString(xmlString, "text/xml");
  1275. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1276. return partNames.reduce((arr: string[], item) => {
  1277. const textContent = item?.textContent?.trim()
  1278. if (textContent !== "COMMON" && textContent) {
  1279. arr.push(textContent)
  1280. }
  1281. return arr
  1282. }, []);
  1283. }
  1284. // 设置音源
  1285. function initMusicSource(data: any, track?: string) {
  1286. const { instrumentId } = storeData.user
  1287. let { musicSheetType, isAllSubject, musicSheetSoundList, musicSheetAccompanimentList } = data
  1288. musicSheetSoundList || (musicSheetSoundList = [])
  1289. musicSheetAccompanimentList || (musicSheetAccompanimentList = [])
  1290. let musicObj, accompanyObj, fanSongObj, banSongObj
  1291. // 独奏
  1292. if (musicSheetType === "SINGLE") {
  1293. // 适用声部(instrumentId)为true 时候没有乐器只有一个原音;当前用户有乐器就匹配 不然取第一个原音
  1294. musicObj = musicSheetSoundList.find((item: any) => {
  1295. return (isAllSubject || !instrumentId) ? item.audioPlayType === "PLAY" : (item.audioPlayType === "PLAY" && item.musicalInstrumentId == instrumentId)
  1296. })
  1297. // 因为可能根据学生的乐器id也找不到曲目所以尝试取第一个
  1298. musicObj || (musicObj = musicSheetSoundList.find((item: any) => {
  1299. return item.audioPlayType === "PLAY"
  1300. }))
  1301. fanSongObj = musicSheetSoundList.find((item: any) => {
  1302. return item.audioPlayType === "SING"
  1303. })
  1304. banSongObj = musicSheetAccompanimentList.find((item: any) => {
  1305. return item.audioPlayType === "SING"
  1306. })
  1307. } else {
  1308. // 合奏 合奏根据声轨来区分原音
  1309. musicObj = track ? musicSheetSoundList.find((item: any) => {
  1310. return item.track === track
  1311. }) : musicSheetSoundList[0]
  1312. }
  1313. accompanyObj = musicSheetAccompanimentList.find((item: any) => {
  1314. return item.audioPlayType === "PLAY"
  1315. })
  1316. // 当没有任何曲目的时候报错
  1317. if (!musicObj?.audioFileUrl && !accompanyObj?.audioFileUrl && !fanSongObj?.audioFileUrl && !banSongObj?.audioFileUrl && !fanSongObj?.solmizationFileUrl) {
  1318. // 并且是midi没有midi文件的时候
  1319. if(data.playMode === "MIDI" && !data.midiFileUrl) {
  1320. // 是预览的时候 不报错
  1321. if(!query.isPreView){
  1322. throw new Error("该曲目无任何音源");
  1323. }
  1324. }
  1325. }
  1326. Object.assign(state, {
  1327. music: musicObj?.audioFileUrl,
  1328. accompany: accompanyObj?.audioFileUrl,
  1329. fanSong: fanSongObj?.audioFileUrl,
  1330. banSong: banSongObj?.audioFileUrl,
  1331. mingSong: fanSongObj?.solmizationFileUrl
  1332. })
  1333. Object.assign(state.beatSong, {
  1334. music: musicObj?.audioBeatMixUrl,
  1335. accompany: accompanyObj?.audioBeatMixUrl,
  1336. fanSong: fanSongObj?.audioBeatMixUrl,
  1337. banSong: banSongObj?.audioBeatMixUrl,
  1338. mingSong: fanSongObj?.solmizationBeatUrl
  1339. })
  1340. return musicObj
  1341. }
  1342. const setState = (data: any, index: number) => {
  1343. // 根据当前文件有没有 设置当前的播放模式
  1344. if(!state.music){
  1345. if(state.accompany){
  1346. state.playSource = "background"
  1347. }else{
  1348. if(state.fanSong){
  1349. state.playType = "sing"
  1350. state.playSource = "music"
  1351. }else if(state.banSong){
  1352. state.playType = "sing"
  1353. state.playSource = "background"
  1354. }else if(state.mingSong){
  1355. state.playType = "sing"
  1356. state.playSource = "mingSong"
  1357. }
  1358. }
  1359. }
  1360. state.appName = "COLEXIU";
  1361. state.detailId = data.bizId;
  1362. state.xmlUrl = data.xmlFileUrl;
  1363. state.paymentType = data.paymentType
  1364. state.partIndex = index >= 0 ? index : 0;
  1365. state.trackId = data.track;
  1366. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1367. // 声部code
  1368. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1369. // 乐器code
  1370. // let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1371. /**
  1372. * 单曲,指法根据用户当前的乐器来显示,如果没有则取musicSheetSoundList第一个track
  1373. */
  1374. const currentInstrumentId = query.instrumentId || storeData.user?.instrumentId;
  1375. let musicalCode = !currentInstrumentId ? data.musicSheetSoundList?.find((item:any)=>{ return item.audioPlayType === "PLAY" })?.track || '' : data.musicSheetSoundList?.find((item: any) => item?.musicalInstrumentId == currentInstrumentId && item.audioPlayType === "PLAY")?.track || '';
  1376. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1377. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1378. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1379. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1380. state.categoriesId = data.musicCategoryId;
  1381. state.categoriesName = data.musicTagNames;
  1382. // state.enableEvaluation = data.isEvaluated ? true : false;
  1383. state.examSongId = data.bizId + "";
  1384. state.cbsExamSongId = data.id + "";
  1385. state.examSongName = data.name;
  1386. state.coverImg = data.musicCover ?? "";
  1387. // 单声部多声轨合并展示
  1388. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1389. // 如果是simple页面,只显示单轨
  1390. if (state.isSimplePage) {
  1391. state.isCombineRender = false;
  1392. }
  1393. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1394. // 解析扩展字段
  1395. if (data.extConfigJson) {
  1396. try {
  1397. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1398. } catch (error) {
  1399. console.error("解析扩展字段错误:", error);
  1400. }
  1401. }
  1402. state.gradualTimes = state.extConfigJson.gradualTimes;
  1403. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1404. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1405. // 是否开启节拍器
  1406. state.needTick = !!data.isPlayBeat
  1407. state.needSingTick = !!data.isPlaySingBeat
  1408. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1409. // 演奏模式是否播mp3节拍器
  1410. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1411. // 演唱模式是否播mp3节拍器
  1412. state.isSingOpenMetronome = data.isPlaySingBeat && !data.isUseSingSystemBeat ? true : false
  1413. state.isShowFingering = data.isShowFingering ? true : false;
  1414. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1415. state.isAppPlay = data.playMode === 'MIDI';
  1416. state.midiUrl = data.midiFileUrl;
  1417. state.parentCategoriesId = data.musicTag;
  1418. state.musicSheetCategoriesId = data.musicCategoryId;
  1419. state.bizMusicCategoryId = data.bizMusicCategoryId
  1420. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1421. state.originSpeed = state.speed = parseFloat(data.playSpeed) || 0;
  1422. // state.originSpeed = state.speed = data.playSpeed;
  1423. // state.playIngSpeed = data.playSpeed;
  1424. const track = data.code || data.track;
  1425. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1426. // 能否评测,根据当前声轨有无伴奏判断
  1427. if (state.isAppPlay) {
  1428. state.enableEvaluation = state.midiUrl ? true : false
  1429. } else {
  1430. state.enableEvaluation = state.accompany || state.music ? true : false
  1431. }
  1432. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1433. // multiTracksSelection 返回为空,默认代表全部分轨
  1434. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1435. // 开启预备小节
  1436. state.isOpenPrepare = true;
  1437. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1438. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1439. // 是否打击乐
  1440. /**
  1441. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1442. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1443. * 打击乐&节奏练习,没有跟练模式
  1444. */
  1445. // state.isPercussion = isRhythmicExercises();
  1446. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1447. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1448. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1449. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1450. // 设置指法
  1451. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1452. /**
  1453. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1454. * 获取指法code
  1455. */
  1456. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1457. state.fingeringInfo = subjectFingering(code);
  1458. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1459. state.musicalCodeId = state.fingeringInfo?.id || 0
  1460. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1461. ; (window as any).DYSubjectId = state.musicalCodeId
  1462. // 开启自定义每行显示的小节数
  1463. ; (window as any).customSectionAmount = true
  1464. // 标识是课堂乐器,用于移调时进行区分处理
  1465. ; (window as any).DYProjectName = 'musicScore';
  1466. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1467. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1468. state.setting.displayFingering = false
  1469. }
  1470. // 如果是PC端,放大曲谱
  1471. state.platform = query.platform?.toLocaleUpperCase() || "";
  1472. if (state.platform === IPlatform.PC) {
  1473. state.zoom = query.zoom || 1.5;
  1474. state.enableEvaluation = false;
  1475. }
  1476. /**
  1477. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1478. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1479. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1480. *
  1481. */
  1482. let pitchTrack = null
  1483. if (state.isConcert) {
  1484. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1485. pitchTrack = data.musicalInstruments?.find((item: any) => item.code?.split(',')[0] === musicalCode)
  1486. } else {
  1487. pitchTrack = data.musicalInstruments?.find((item: any) => item.code?.split(',')[0] === musicalCode)
  1488. }
  1489. let musicalRenderType = ''
  1490. // if (pitchTrack?.defaultScore) {
  1491. // musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1492. // }
  1493. // state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1494. /**
  1495. * 2024.7.30,使用新的字段
  1496. * 谱面类型,scoreType
  1497. * STAVE("五线谱"),JIAN("固定调"),FIRST("首调"),
  1498. */
  1499. musicalRenderType = data.scoreType === 'STAVE' ? 'staff' : data.scoreType === 'JIAN' ? 'fixedTone' : data.scoreType === 'FIRST' ? '' : 'firstTone';
  1500. if (!state.isEvaluatReport) {
  1501. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1502. }
  1503. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1504. /**
  1505. * TODO:摇篮曲特殊处理
  1506. */
  1507. if (['1788501975122489346', '1788502467554750466', '1789839575249596417'].includes(state.cbsExamSongId)) {
  1508. if (state.musicRenderType === 'fixedTone') {
  1509. state.musicRenderType = EnumMusicRenderType.firstTone;
  1510. }
  1511. }
  1512. /**
  1513. * 2024.7.30,使用新的字段
  1514. * 能否转谱,isConvertibleScore
  1515. * true:能转谱,false:不能转谱
  1516. * 额外的逻辑:后台设置不能转谱时,如果默认谱面不是五线谱,需要显示转谱按钮,但是只能转首调和固定调
  1517. */
  1518. // state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1519. state.enableNotation = data.isConvertibleScore
  1520. state.specialShowNotation = !data.isConvertibleScore && data.scoreType !== 'STAVE';
  1521. console.log("state对象", state);
  1522. // 评测基准频率
  1523. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1524. state.baseFrequency = Number(state.baseFrequency)
  1525. // 用户上次的频率和基准频率误差超过10,则重置
  1526. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1527. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1528. } else {
  1529. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1530. }
  1531. };
  1532. // 多分轨合并显示标示
  1533. const setCustom = (trackNum?: number) => {
  1534. if (trackNum || state.extConfigJson.multitrack) {
  1535. state.multitrack = trackNum || 0
  1536. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1537. }
  1538. };
  1539. /** 跟练模式播放节拍器(叮咚) */
  1540. export const followBeatPaly = () => {
  1541. let metroTimer: any = null;
  1542. if (!followData.start) {
  1543. clearTimeout(metroTimer)
  1544. metroTimer = null
  1545. return;
  1546. }
  1547. const time = state.measureTime * 1000 / metronomeData.totalNumerator / state.basePlayRate;
  1548. requestAnimationFrame(() => {
  1549. const endTime = Date.now();
  1550. if (endTime - state.beatStartTime < time) {
  1551. followBeatPaly();
  1552. } else {
  1553. // metroTimer = setTimeout(() => {
  1554. // metronomeData.metro?.simulatePlayAudio()
  1555. // startTime = Date.now();
  1556. // followBeatPaly();
  1557. // }, time);
  1558. metronomeData.metro?.simulatePlayAudio()
  1559. state.beatStartTime = Date.now();
  1560. followBeatPaly();
  1561. }
  1562. });
  1563. };
  1564. // 音符添加bbox
  1565. export const addNoteBBox = (list: any[]) => {
  1566. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  1567. x: 0,
  1568. y: 0,
  1569. };
  1570. const parentLeft = musicContainer.x || 0;
  1571. let voicesBBox: any = null;
  1572. for (let i = 0; i < list.length; i++) {
  1573. const note = list[i];
  1574. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1575. /**
  1576. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1577. */
  1578. let bbox: any = null;
  1579. if (svgElement?.attrs.id) {
  1580. // @ts-ignore
  1581. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1582. const noteBbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBoundingClientRect?.() || { x: 0, width: 0 };
  1583. bbox = {
  1584. left: noteBbox.x - parentLeft - noteBbox.width / 4, // 用于简谱模式,跳动音符时,设置光标的位置(五线谱:osmd自动设置光标位置,简谱:需要手动设置光标位置)
  1585. x: bbox?.x * state.zoom,
  1586. y: bbox?.y * state.zoom,
  1587. width: bbox?.width * state.zoom,
  1588. height: bbox?.height * state.zoom,
  1589. }
  1590. } else {
  1591. // @ts-ignore
  1592. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1593. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1594. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1595. currentVoicesBBox = voicesBBox;
  1596. }
  1597. let nextIndex = i + 1;
  1598. while (!list[nextIndex]?.id && nextIndex < list.length) {
  1599. nextIndex += 1;
  1600. }
  1601. // 休止小节的开头和下一个音符之间的间距
  1602. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1603. if (list[nextIndex]?.id) {
  1604. // @ts-ignore
  1605. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1606. }
  1607. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1608. bbox = currentVoicesBBox ? {
  1609. bottom: currentVoicesBBox.bottom,
  1610. height: 30,
  1611. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1612. right: currentVoicesBBox.y,
  1613. top: currentVoicesBBox.top,
  1614. width: 1,
  1615. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1616. y: currentVoicesBBox.y,
  1617. svgBodyLeft: svgBodyBBox?.x,
  1618. } : null;
  1619. voicesBBox = currentVoicesBBox;
  1620. }
  1621. // todo 连续修止小节bug
  1622. note.bbox = bbox;
  1623. }
  1624. }
  1625. // 给歌词和音符添加动态颜色
  1626. export const fillWordColor = () => {
  1627. // console.log('当前音符',state.activeNoteIndex)
  1628. state.times.forEach((item: any, idx: number) => {
  1629. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1630. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1631. const stemLine = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-lines`)
  1632. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1633. svgEl?.classList.add('noteActive')
  1634. stemEl?.classList.add('noteActive')
  1635. stemLine?.classList.add('noteActive')
  1636. } else {
  1637. svgEl?.classList.remove('noteActive')
  1638. stemEl?.classList.remove('noteActive')
  1639. stemLine?.classList.remove('noteActive')
  1640. }
  1641. })
  1642. // 给当前匹配到的歌词添加颜色
  1643. const currentNote = state.times[state.activeNoteIndex];
  1644. const lyrics: SVGAElement[] = Array.from(document.querySelectorAll(".vf-lyric"));
  1645. lyrics.forEach((lyric) => {
  1646. lyric?.classList.remove('lyricActive')
  1647. })
  1648. const currentLyrics: SVGAElement[] = Array.from(document.querySelectorAll(`.lyric${currentNote?.noteId}`));
  1649. currentLyrics.forEach((lyric, index) => {
  1650. const lyricIndex = lyric.getAttribute('lyricIndex');
  1651. if ((index === currentNote.repeatIdx && currentNote.repeatIdx + 1 == lyricIndex) || (currentNote.repeatIdx > 0 && currentNote.formatLyricsEntries?.length === 1)) {
  1652. lyric?.classList.add('lyricActive')
  1653. }
  1654. })
  1655. }
  1656. /** 跳动svgdom */
  1657. export const moveSvgDom = (skipNote?: boolean) => {
  1658. /**
  1659. * 计算需要移动的距离
  1660. * 当前选中的音符和第一个音符之间的间距
  1661. */
  1662. if (skipNote) {
  1663. // 点击 清空translateXNum
  1664. smoothAnimationState.translateXNum = 0
  1665. moveTranslateXNum(0)
  1666. // 移动小鸟的位置
  1667. moveSmoothAnimation(0, state.activeNoteIndex, false)
  1668. // 移动谱面当当前音符的位置
  1669. const noteWidth = state.times[state.activeNoteIndex].bbox?.originWidth || state.times[state.activeNoteIndex].bbox?.width;
  1670. const firstNoteWidth = state.times[0].bbox?.originWidth || state.times[0].bbox?.width;
  1671. const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + noteWidth / 2 - firstNoteWidth / 2;
  1672. smoothAnimationState.osdmScrollDom!.scrollTo({
  1673. left: distance,
  1674. behavior: "smooth",
  1675. });
  1676. }
  1677. }
  1678. // 暂停的时候 恢复一行谱偏移位置信息
  1679. watch(
  1680. () => state.playState,
  1681. () => {
  1682. if (state.isSingleLine) {
  1683. // 当在播放中暂停 执行这个方法
  1684. if (!state.playEnd && state.playState === "paused") {
  1685. moveTranslateXNum(0)
  1686. // 因为safari浏览器scrollWidth的值一直变化,scrollLeft + smoothAnimationState.translateXNum 为最大宽度的时候,实际上scrollLeft滚不到最大宽度,所以在下一帧处理滚动,能滚动到最大滚动位置
  1687. requestAnimationFrame(() => {
  1688. const scrollLeft = smoothAnimationState.osdmScrollDom!.scrollLeft
  1689. smoothAnimationState.osdmScrollDom!.scrollLeft = scrollLeft + smoothAnimationState.translateXNum
  1690. smoothAnimationState.translateXNum = 0
  1691. });
  1692. }
  1693. }
  1694. }
  1695. )
  1696. /* 根据当前的小节获取前面有多少需要去除的合并小节 */
  1697. function getNeedReduceMultipleRestNum(currMeasureIndex: number) {
  1698. let needReduceMultipleRestNum = 0;
  1699. for (let noteIndex = 0; noteIndex < state.times.length; noteIndex++) {
  1700. const note = state.times[noteIndex];
  1701. if (note.MeasureNumberXML > currMeasureIndex) {
  1702. break;
  1703. }
  1704. if (note.multipleRestMeasures && note.multipleRestMeasures > 1) {
  1705. needReduceMultipleRestNum += 1;
  1706. }
  1707. }
  1708. return needReduceMultipleRestNum
  1709. }
  1710. watch(
  1711. () => state.activeMeasureIndex,
  1712. () => {
  1713. // 需要减去的合并小节数
  1714. // const needReduceMultipleRestNum = getNeedReduceMultipleRestNum(state.activeMeasureIndex)
  1715. // const matchMeasureNum = state.activeMeasureIndex - needReduceMultipleRestNum - 1
  1716. // console.log('选中的小节',matchMeasureNum,'需要减去的小节',needReduceMultipleRestNum,'当前的小节',state.activeMeasureIndex)
  1717. state.vfmeasures.forEach((item: any, idx: number) => {
  1718. const measureNum = item.getAttribute('data-num') ? Number(item.getAttribute('data-num')) : -1;
  1719. const nextMeasureNum = state.vfmeasures[idx+1]?.getAttribute('data-num') ? Number(state.vfmeasures[idx+1]?.getAttribute('data-num')) : -1;
  1720. if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex)) ) {
  1721. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#132D4C")
  1722. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#040D1E")
  1723. // 预备小节
  1724. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
  1725. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "#71B8BD")
  1726. item?.querySelector('.vf-custom-bot')?.setAttribute("fill", "#448F9C")
  1727. }
  1728. } else {
  1729. // 有选段只清除选段处的
  1730. if (state.section.length === 2) {
  1731. // 把中间置灰
  1732. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  1733. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  1734. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  1735. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  1736. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  1737. }
  1738. if(measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML){
  1739. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1740. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1741. }
  1742. // 预备小节
  1743. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
  1744. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "#71B8BD")
  1745. item?.querySelector('.vf-custom-bot')?.setAttribute("fill", "#448F9C")
  1746. }
  1747. } else {
  1748. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1749. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1750. }
  1751. }
  1752. })
  1753. }
  1754. );
  1755. watch(
  1756. () => state.section,
  1757. () => {
  1758. if (state.section.length === 2) {
  1759. // 把前面和 后面置灰
  1760. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  1761. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  1762. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  1763. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  1764. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  1765. }
  1766. state.vfmeasures.forEach((item: any, idx: number) => {
  1767. const measureNum = item.getAttribute('data-num') ? Number(item.getAttribute('data-num')) : 1;
  1768. // 小于选中置灰
  1769. if (measureNum < leftMeasureNumberXML) {
  1770. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(96,159,207,0.5)")
  1771. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "rgba(43,112,165,0.5)")
  1772. }
  1773. // 大于选中置灰
  1774. if(measureNum > rightMeasureNumberXML){
  1775. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(96,159,207,0.5)")
  1776. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "rgba(43,112,165,0.5)")
  1777. }
  1778. // 预备小节
  1779. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
  1780. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "#71B8BD")
  1781. item?.querySelector('.vf-custom-bot')?.setAttribute("fill", "#448F9C")
  1782. }
  1783. })
  1784. }else{
  1785. // 恢复选段前
  1786. state.vfmeasures.forEach((item: any, idx: number) => {
  1787. const measureNum = item.getAttribute('data-num') ? Number(item.getAttribute('data-num')) : -1;
  1788. const nextMeasureNum = state.vfmeasures[idx+1]?.getAttribute('data-num') ? Number(state.vfmeasures[idx+1]?.getAttribute('data-num')) : -1;
  1789. if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex)) ) {
  1790. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#132D4C")
  1791. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#040D1E")
  1792. } else {
  1793. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1794. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1795. }
  1796. })
  1797. }
  1798. }
  1799. )
  1800. /** 刷新谱面 */
  1801. export const refreshMusicSvg = () => {
  1802. clearSelection();
  1803. resetBaseRate();
  1804. state.activeMeasureIndex = -1;
  1805. if (query.workRecord) {
  1806. state.workSectionNeedReset = true;
  1807. }
  1808. // 销毁旋律线
  1809. destroySmoothAnimation()
  1810. musicScoreRef.value?.refreshMusicScore()
  1811. }
  1812. // 指法改变显示的时候 osdmScrollDomWith 宽度会变化 所以指法改变的时候这个宽度重新计算
  1813. watch(
  1814. () => state.setting.displayFingering,
  1815. () => {
  1816. // 有字符 并且是竖向指法 并且是一行谱
  1817. if(state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && state.isSingleLine){
  1818. nextTick(() => {
  1819. calcClientWidth()
  1820. })
  1821. }
  1822. // 如果有指法,并且是竖向指法时,切换指法时,谱面宽度变化,需要重新渲染谱面
  1823. if (state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && !state.isSingleLine) {
  1824. headTopData.settingMode = false;
  1825. refreshMusicSvg();
  1826. }
  1827. }
  1828. )