state.ts 90 KB

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