state.ts 78 KB

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