state.ts 80 KB

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