state.ts 82 KB

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