state.ts 87 KB

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