state.ts 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  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. musicBuyInfo: null as any,
  555. // vip类型 VIP:会员 SVIP:SVIP,PERMANENT_SVIP:永久SVIP,NOT_VIP:不是vip
  556. vipType: '' as any,
  557. /** 播放模式,默认练习模式 */
  558. defaultModeType: 1,
  559. /** 音符最多歌词次数 */
  560. maxLyricNum: 0,
  561. /** 小节dom集合 */
  562. vfmeasures: [] as SVGAElement[],
  563. /** 作曲家 */
  564. musicComposer: '',
  565. /** 作词家 */
  566. musicLyricist: '',
  567. // 加载条
  568. isLoading: true,
  569. /** 加载中的文案 */
  570. loadingText: '音频资源加载中,请稍后…',
  571. /** 是否是简单的单行谱模式页面 */
  572. isSimplePage: false,
  573. /** xml的速度和后台设置的速度,计算出的基础音频播放倍率 */
  574. originAudioPlayRate: 1,
  575. /** 开始播放时,记录的mp3播放倍率,用户当前设置的速度/当前小节的速度 */
  576. basePlayRate: 1,
  577. /** 引导页显示状态 */
  578. hasDriverPop: false,
  579. /** 播放倍率不等于1,或者是选段评测,APP暂时不支持保存演奏,需要给出提示 */
  580. noSavePopShow: true,
  581. /** xml里面是否有歌词 */
  582. xmlHasLyric: false,
  583. /** 生成图片的模式 */
  584. isCreateImg: false,
  585. /** 切换谱面后,作业选段是否需要刷新 */
  586. workSectionNeedReset: false,
  587. /** 旋律线开关 */
  588. melodyLine: false,
  589. /** 是否是C调,切换到唱名时,只有C调所有的谱面类型都可以播放唱名文件;其它调的只有首调可以播放唱名,因为唱名是按照C调制作的,没有其它调的唱名文件 */
  590. isCTone: false,
  591. evxmlAddPartName: false, // 妙极客的部分曲子没有part-name,需要自行添加的part-name
  592. /** 乐器id */
  593. instrumentId: null,
  594. /** 是否是作业模式(包含练习和评测) */
  595. isHomeWork: false,
  596. /** 顶部栏高度 */
  597. headTopHeight: 0,
  598. /** 是否是自动重播,练习模式开启自动重播时,播放前不需要再次计算播放倍率了,还是按照上次的播放倍率播放音频 */
  599. isAutoRePlay: false,
  600. /** 跟练,是否收到了录音的回调 */
  601. hasFollowResult: false,
  602. /** 右上角速度图标,根据当前小节的速度是几分音符的动态变化 */
  603. speedIcon: 'speed3', // 默认取1/4拍的图片
  604. /** xml的第一个measure标签的number */
  605. firstMeasureNumber: 1,
  606. /** 曲目点播价格 */
  607. musicPrice: 0,
  608. /** 专辑id */
  609. tenantAlbumId: '',
  610. /** 平台或者机构 */
  611. providerType: "PLATFORM" as "PLATFORM" | "TENANT",
  612. /** 后台审核 */
  613. isWebAudit: false,
  614. /** 是否是单声轨多声部的声轨 */
  615. isSingleMutliTrack: false,
  616. });
  617. const browserInfo = browser();
  618. let offset_duration = 0;
  619. /** 自定义数据 */
  620. export const customData = reactive({
  621. /** 自定义音符时值 */
  622. customNoteRealValue: [] as any,
  623. /** 自定义音符按读取到的时值 */
  624. customNoteCurrentTime: false,
  625. });
  626. /** 在渲染前后计算光标应该走到的音符 */
  627. export const setStep = () => {
  628. // console.log('播放状态',state.playState)
  629. if (state.playState !== "play") {
  630. // TODO:bug:11905,ios白屏偶现问题
  631. if (storeData.isApp && (browserInfo.ios || browserInfo.iPhone) ) {
  632. const osmdDom = document.getElementById('osmdCanvasPage1')
  633. if (osmdDom) {
  634. osmdDom.style.zIndex = '0';
  635. requestAnimationFrame(() => {
  636. osmdDom.style.zIndex = '1';
  637. })
  638. }
  639. }
  640. console.log("暂停播放");
  641. return;
  642. }
  643. let startTime = Date.now();
  644. requestAnimationFrame(() => {
  645. const endTime = Date.now();
  646. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  647. if (endTime - startTime < 16.7) {
  648. handlePlaying();
  649. setStep();
  650. } else {
  651. setTimeout(() => {
  652. handlePlaying();
  653. setStep();
  654. }, 16.7);
  655. }
  656. });
  657. };
  658. /** 开始播放 */
  659. export const onPlay = () => {
  660. console.log("开始播放", '音频总时长:', getAudioDuration());
  661. state.playEnd = false;
  662. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  663. offset_duration = 0.2;
  664. setStep();
  665. };
  666. /** 播放模式结束自动重播 */
  667. const autoResetPlay = () => {
  668. if (state.modeType !== "practise") return;
  669. // 如果是选段需要跳转到预备小节或者选段内的第一小节,否则跳转到第一小节
  670. const targetIdx = state.section.length === 2 ? state.sectionFirst?.i || state.section[1].i : 0;
  671. skipNotePlay(targetIdx, true);
  672. // 没有开启自动重播, 不是练习模式
  673. if (!state.setting.repeatAutoPlay) return;
  674. offsetTop = 0;
  675. scrollViewNote();
  676. setTimeout(() => {
  677. // 自动播放,不需要再次计算播放倍率
  678. state.isAutoRePlay = true;
  679. togglePlay("play");
  680. }, 1000);
  681. };
  682. /** 播放完成事件 */
  683. export const onEnded = () => {
  684. console.log("音频播放结束");
  685. // if (state.isAppPlay) {
  686. // // 销毁播放器
  687. // api_cloudDestroy();
  688. // }
  689. if (state.playEnd) {
  690. console.log('音频播放结束,无需再次执行')
  691. return
  692. }
  693. // 修改状态为结束
  694. state.playEnd = true;
  695. state.playState = "paused";
  696. // 结束播放
  697. audioListStart(state.playState);
  698. // 调用结束评测
  699. handleEndEvaluat(true);
  700. // 调用自动重复播放
  701. autoResetPlay();
  702. };
  703. // 根据当前小节动态设置,右上角展示的速度
  704. const dynamicShowPlaySpeed = (index: number, isPlaying?: boolean) => {
  705. //if (!headerColumnHide.value) {
  706. const item: any = state.times[index];
  707. if (item && item.measureSpeed ) {
  708. // console.log('速度1',item.measureSpeed)
  709. const newSpeed = state.basePlayRate * item.measureSpeed
  710. if (state.speed !== newSpeed) {
  711. state.speed = newSpeed;
  712. }
  713. }
  714. //}
  715. }
  716. // 开始播放时,计算mp3的播放倍率
  717. export const initSetPlayRate = () => {
  718. // 自动播放,不需要再次计算播放倍率
  719. if (state.isAutoRePlay) {
  720. state.isAutoRePlay = false
  721. return
  722. }
  723. // let item: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
  724. let item: any = state.times[state.activeNoteIndex];
  725. console.log('播放状态',state.playState)
  726. if (item && item.measureSpeed) {
  727. const ratio = state.speed / item.measureSpeed
  728. // state.audiosInstance?.setSpeed(ratio)
  729. state.basePlayRate = ratio || 1;
  730. console.log('播放倍率',state.basePlayRate)
  731. }
  732. }
  733. // 重置播放倍率
  734. export const resetBaseRate = (idx?: number) => {
  735. const index = idx ? idx : 0;
  736. let currentItem: any = state.times[index];
  737. const currentSpeed = currentItem?.measureSpeed ? currentItem.measureSpeed : state.originSpeed;
  738. // console.log('速度2',currentSpeed)
  739. state.speed = currentSpeed
  740. //state.activeNoteIndex = 0
  741. state.basePlayRate = 1;
  742. }
  743. /**
  744. * 播放一直触发的事件
  745. */
  746. const handlePlaying = () => {
  747. const currentTime = getAudioCurrentTime();
  748. const duration = getAudioDuration();
  749. state.playProgress = (currentTime / duration) * 100;
  750. let item = getNote(currentTime);
  751. if (item) {
  752. // 选段状态下
  753. if (state.sectionStatus && state.section.length === 2) {
  754. // 如果开启了预备拍
  755. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  756. const selectEndItem = state.section[1];
  757. if (currentTime - selectEndItem.endtime >= 0) {
  758. console.log("选段播放结束", state.setting.repeatAutoPlay);
  759. // 如果为选段评测模式
  760. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  761. onEnded();
  762. return;
  763. }
  764. // #8698 bug修复
  765. if (state.modeType === "practise" && state.sectionStatus) {
  766. // 练习作业,练习完一次需要增加练习次数
  767. if (query.workRecord) {
  768. HANDLE_WORK_ADD()
  769. }
  770. onEnded();
  771. // state.activeNoteIndex = state.sectionFirst ? state.sectionFirst.i : state.section[0].i
  772. // dynamicShowPlaySpeed(state.activeNoteIndex)
  773. resetPlaybackToStart();
  774. return;
  775. }
  776. item = selectStartItem;
  777. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  778. }
  779. /**
  780. * #9374,反复小节的曲目播放错误, bug修复
  781. * 曲目:噢!苏珊娜-排箫-人音
  782. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  783. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  784. */
  785. if (state.repeatInfo.length) {
  786. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  787. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  788. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  789. const preItem = state.times[item.i - 1]
  790. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  791. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  792. if (skipItem) {
  793. // 跳转到指定的音频位置
  794. setAudioCurrentTime(skipItem.time, skipItem.i);
  795. gotoNext(skipItem);
  796. return
  797. }
  798. }
  799. }
  800. }
  801. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  802. // if (currentTime - selectEndItem.endtime > offset_duration) {
  803. //console.log(currentTime,selectEndItem.endtime)
  804. }
  805. gotoNext(item);
  806. dynamicShowPlaySpeed(item.i, true);
  807. }
  808. // 评测不播放叮咚节拍器
  809. // if (state.modeType !== "evaluating") {
  810. // metronomeData.metro?.sound(currentTime);
  811. // }
  812. // 不需要播放节拍器的声音,因为音频带有节拍器的声音
  813. metronomeData.metro?.sound(currentTime);
  814. // 一行谱,需要滚动小节
  815. if (state.isSingleLine) {
  816. moveSmoothAnimationByPlayTime()
  817. }
  818. };
  819. /** 跳转到指定音符开始播放 */
  820. export const skipNotePlay = async (itemIndex: number, isStart = false, handType?: string) => {
  821. // 纯预览模式,练习、评测作业模式,禁止手动点击跳转音符
  822. if (state.isPreView) return;
  823. // 点击或者重播的时候清除一行谱的时间信息
  824. state.isSingleLine && (smoothAnimationState.oldCurrentTime = 0)
  825. if (handType === 'manual' && (query.workRecord || query.evaluatingRecord)) return;
  826. const item = state.times[itemIndex];
  827. // 如果是选段状态,可以点击段落范围内的音符,从当前音符开始播放,如果不是段落内的音符,直接return
  828. if (handType === 'manual' && state.section.length === 2 && !(item.MeasureNumberXML >= state.section[0].MeasureNumberXML && item.MeasureNumberXML <= state.section[1].MeasureNumberXML)) {
  829. return;
  830. }
  831. console.log('点击音符')
  832. let itemTime = item.time;
  833. if (isStart) {
  834. itemTime = 0;
  835. }
  836. if (item) {
  837. // 非选段模式,点击音符,动态设置右下角的速度
  838. if (item.measureSpeed && state.section.length < 2) {
  839. // console.log('速度3')
  840. state.speed = state.basePlayRate * 1000000 * item.measureSpeed / 1000000
  841. }
  842. setAudioCurrentTime(itemTime, itemIndex);
  843. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  844. gotoNext(item, true);
  845. // 不需要播放节拍器的声音,因为音频带有节拍器的声音
  846. // metronomeData.metro?.sound(itemTime);
  847. metronomeData?.metro?.findMetronomePosition(itemTime);
  848. if (state.isAppPlay) {
  849. await api_cloudSetCurrentTime({
  850. currentTime: itemTime * 1000,
  851. songID: state.examSongId,
  852. })
  853. audioData.progress = itemTime
  854. state.midiSectionStart = itemTime
  855. }
  856. // 如果是跟练模式
  857. if (followData.start) {
  858. skipNotePractice()
  859. }
  860. }
  861. };
  862. /**
  863. * 切换曲谱播放状态
  864. * @param playState 需要切换的状态 play:播放, paused: 暂停
  865. */
  866. export const togglePlay = async (playState: "play" | "paused", isForceCLoseToast?:boolean) => {
  867. // 如果mp3资源还在加载中,给出提示
  868. if (!state.isAppPlay && !state.audioDone) {
  869. if (!isForceCLoseToast) showToast('音频资源加载中,请稍后')
  870. return
  871. }
  872. // 播放之前 当为评测模式和不为MIDI时候按 是否禁用节拍器 切换音源
  873. if (playState === 'play' && state.modeType === "practise" && state.playMode !== "MIDI") {
  874. console.log("设置音源")
  875. changeSongSourceByBeat(metronomeData.disable)
  876. }
  877. if (playState === 'play') {
  878. offsetTop = 0;
  879. scrollViewNote();
  880. }
  881. // midi播放
  882. if (state.isAppPlay) {
  883. if (playState === "paused") {
  884. await api_cloudSuspend({
  885. songID: state.examSongId,
  886. })
  887. state.playState = 'paused'
  888. // 当在节拍器播放期间暂停的话 就暂停节拍器
  889. closeTick()
  890. return
  891. }
  892. skipNotePlay(state.activeNoteIndex, false);
  893. await api_cloudChangeSpeed({
  894. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  895. originalSpeed: state.originSpeed,
  896. songID: state.examSongId,
  897. });
  898. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  899. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  900. state.playState = status
  901. } else {
  902. state.playState = playState;
  903. }
  904. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  905. resetPlaybackToStart();
  906. }
  907. // 当在节拍器播放期间暂停的话 就暂停节拍器
  908. if (state.playState === "paused") {
  909. closeTick()
  910. }
  911. // 设置为开始播放时, 如果需要节拍,先播放节拍器 只有在当前播放时间不为0的时候开启节拍器
  912. const isOneMeasureNumberXML = state.section.length === 2 && state.section[0].MeasureNumberXML === 2 //当是选段模式 并且开始小节是第二小节 就不播节拍器(这种情况有预选小节,currentTime是0)
  913. if (state.playState === "play" && getAudioCurrentTime() === 0 && !isOneMeasureNumberXML && ((state.playType === "play" && state.needTick) || (state.playType === "sing" && state.needSingTick))) {
  914. // 如果是系统节拍器 等系统节拍器播完了再播,如果是mp3节拍器 直接播
  915. if ((state.playType === "play" && !state.isOpenMetronome) || (state.playType === "sing" && !state.isSingOpenMetronome)) {
  916. const tickend = await handleStartTick();
  917. // console.log("🚀 ~ tickend:", tickend)
  918. // 节拍器返回false, 取消播放
  919. if (!tickend) {
  920. state.playState = "paused";
  921. return false;
  922. }
  923. } else {
  924. handleStartTick()
  925. }
  926. }
  927. // 如果选段没有结束, 直接开始播放,清空选段状态
  928. if (state.playState == "play") {
  929. if (state.sectionStatus && state.section.length < 2) {
  930. clearSelection();
  931. }
  932. }
  933. initSetPlayRate();
  934. audioListStart(state.playState);
  935. return true;
  936. };
  937. /** 结束播放 */
  938. export const handleStopPlay = () => {
  939. state.playState = "paused";
  940. audioListStart(state.playState);
  941. };
  942. /** 重置播放为开始 */
  943. export const resetPlaybackToStart = () => {
  944. // 如果为选段状态
  945. if (state.sectionStatus && state.section.length === 2) {
  946. state.section = formateSelectMearure(state.section);
  947. return;
  948. } else {
  949. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  950. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  951. }
  952. skipNotePlay(0, true);
  953. };
  954. /** 跳转到指定音符 */
  955. export const gotoCustomNote = (index: number) => {
  956. console.log('跳转位置1111',index)
  957. try {
  958. state.osmd.cursor.reset();
  959. } catch (error) { }
  960. for (let i = 0; i < index; i++) {
  961. state.osmd.cursor.next();
  962. }
  963. };
  964. // 找出离目标元素最近的音符
  965. const computedDistance = (x: number, y: number) => {
  966. let minDistance = -1, minidx = 0;
  967. let a, b, c;
  968. state.noteCoords.forEach((note: any, idx: any) => {
  969. //a,b为直角三角形的两个直角边
  970. a = Math.abs(note.x - x)
  971. b = Math.abs(note.y - y)
  972. //c为直角三角形的斜边
  973. c = Math.sqrt(a * a + b * b) as 0
  974. c = Number(c.toFixed(0)) as 0
  975. if (c !== 0 && (minDistance === - 1 || c < minDistance)) {
  976. //min为元素中离目标元素最近元素的距离
  977. minDistance = c
  978. minidx = idx
  979. }
  980. })
  981. return minidx
  982. };
  983. const setCursorPosition = (note: any, cursor: any, flag?: string) => {
  984. // console.log('音符',note?.i,state.osmd.Cursor.noteGraphicalId,note.svgElement?.attrs?.id)
  985. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  986. /**
  987. * bug:#9920、#9940
  988. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  989. */
  990. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  991. return
  992. }
  993. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  994. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  995. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  996. const cursorLeft = cursor?.cursorElement?.style?.left ? parseFloat(cursor.cursorElement.style.left) : 0;
  997. let patchX = 0;
  998. if (state.cbsExamSongId == '1788502467554750466') {
  999. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  1000. 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;
  1001. }
  1002. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  1003. 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;
  1004. }
  1005. } else if (state.cbsExamSongId == '1788501975122489346') {
  1006. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  1007. 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;
  1008. }
  1009. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  1010. 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;
  1011. }
  1012. }
  1013. if (flag === 'refresh' || (flag === 'init' && !state.specialPosInit)) {
  1014. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  1015. cursor.cursorElement.style.left = cursorLeft + patchX + "px";
  1016. state.specialPosInit = true;
  1017. }
  1018. } else {
  1019. nextTick(() => {
  1020. let bbox = note.bbox;
  1021. if (!bbox) {
  1022. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  1023. x: 0,
  1024. y: 0,
  1025. };
  1026. const parentLeft = musicContainer.x || 0;
  1027. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  1028. if (noteEle) {
  1029. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  1030. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  1031. if (noteHeadBbox) {
  1032. note.bbox = {
  1033. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  1034. width: noteHeadBbox.width * 1.5,
  1035. };
  1036. bbox = note.bbox;
  1037. }
  1038. }
  1039. }
  1040. if (!bbox) return;
  1041. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  1042. const width = (bbox.width - baseW) / 3;
  1043. // console.log(555555,bbox.left,width)
  1044. cursor.cursorElement.style.left = bbox.left + "px";
  1045. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  1046. });
  1047. }
  1048. }
  1049. };
  1050. /**
  1051. * 跳转到下一个音符
  1052. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  1053. **/
  1054. export const gotoNext = (note: any, skipNote?: boolean) => {
  1055. // console.log(33333333333,state.activeNoteIndex,note.i)
  1056. const num = note.i;
  1057. if (state.activeNoteIndex === note.i) {
  1058. /* 没有光标了 这里就算加上光标也要性能优化 */
  1059. // try {
  1060. // setCursorPosition(note, state.osmd.cursor, 'init');
  1061. // } catch (error) {
  1062. // console.log(error);
  1063. // }
  1064. // 重置 或者切换演奏演唱的时候 可能出现 state.activeNoteIndex === note.i的情况 执行
  1065. if(state.playState === "paused"){
  1066. // fillWordColor();
  1067. }
  1068. if (state.isSingleLine && state.playState === "paused") {
  1069. moveSvgDom(skipNote);
  1070. }
  1071. return;
  1072. }
  1073. const osmd = state.osmd;
  1074. let prev = state.activeNoteIndex;
  1075. state.activeNoteIndex = num;
  1076. state.activeMeasureIndex = note.MeasureNumberXML;
  1077. osmd.cursor.activeMeasureNum = note.MeasureNumberXML;
  1078. // 赋值音符id
  1079. osmd.cursor.noteGraphicalId = state.times[state.activeNoteIndex].id;
  1080. // 设置光标位置
  1081. // nextTick(() => {
  1082. // if (osmd.cursor.noteGraphicalId) {
  1083. // const { x, y } = document.getElementById(`vf-${osmd.cursor.noteGraphicalId}`)?.getBoundingClientRect() || { x: 0, y: 0}
  1084. // osmd.cursor.cursorElement.style.left = x + "px";
  1085. // // cursorElement.style.top = y + "px";
  1086. // }
  1087. // })
  1088. dynamicShowPlaySpeed(state.activeNoteIndex);
  1089. if (prev && num - prev === 1) {
  1090. // console.log('跳转音符',11111,osmd.cursor)
  1091. // if (!note.id && note.multipleRestMeasures === 0) {
  1092. // } else {
  1093. // osmd.cursor.next();
  1094. // }
  1095. osmd.cursor.next();
  1096. } else if (prev >= 0 && num - prev > 0) {
  1097. while (num - prev > 0) {
  1098. prev++;
  1099. // console.log('跳转音符',22222)
  1100. osmd.cursor.next();
  1101. }
  1102. } else if (prev >= 0) {
  1103. // gotoCustomNote(num);
  1104. while (prev - num > 0) {
  1105. prev--;
  1106. // console.log('跳转音符',22222)
  1107. osmd.cursor.previous();
  1108. }
  1109. }
  1110. /* 取消光标了 */
  1111. // try {
  1112. // setCursorPosition(note, state.osmd.cursor, 'refresh');
  1113. // } catch (error) {
  1114. // console.log(error);
  1115. // }
  1116. // fillWordColor();
  1117. // 一行谱,需要滚动小节
  1118. if (state.isSingleLine && state.playState === "paused") {
  1119. moveSvgDom(skipNote);
  1120. }
  1121. scrollViewNote();
  1122. };
  1123. /** 获取指定音符 */
  1124. export const getNote = (currentTime: number) => {
  1125. const times = state.times;
  1126. const len = state.times.length;
  1127. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  1128. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay && !state.isSimplePage) {
  1129. // onEnded();
  1130. return;
  1131. }
  1132. let _item = null as any;
  1133. for (let i = state.activeNoteIndex; i < len; i++) {
  1134. let item = times[i];
  1135. const prevItem = times[i - 1];
  1136. // if (state.isEvxml) {
  1137. // let diffArr: any[] = [];
  1138. // times.forEach((note: any, noteIdx: number) => {
  1139. // if (currentTime >= note.time && currentTime <= times[noteIdx+1].time) {
  1140. // let diffTime = times[noteIdx+1].time - currentTime;
  1141. // diffArr.push({
  1142. // diffTime,
  1143. // idx: noteIdx
  1144. // })
  1145. // }
  1146. // })
  1147. // diffArr.sort((a, b) => a.diffTime - b.diffTime);
  1148. // item = diffArr.length ? times[diffArr[0].idx] : item;
  1149. // }
  1150. if (currentTime >= item.time) {
  1151. if (!prevItem || item.time != prevItem.time) {
  1152. _item = item;
  1153. }
  1154. } else {
  1155. break;
  1156. }
  1157. }
  1158. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  1159. return _item;
  1160. };
  1161. /** 重播 */
  1162. export const handleResetPlay = () => {
  1163. // 如果是midi需要重置播放进度
  1164. if (state.isAppPlay) {
  1165. audioData.progress = 0
  1166. }
  1167. // 如果是作业模式,不还原速度
  1168. /**
  1169. * #TODO:2024.09.14,业务需求变更,重播不还原用户设置的速度
  1170. */
  1171. // if (!query.workRecord) {
  1172. // resetBaseRate();
  1173. // }
  1174. resetPlaybackToStart();
  1175. // 如果是暂停, 直接播放
  1176. togglePlay("play");
  1177. };
  1178. /** 设置速度 */
  1179. export const handleSetSpeed = (speed: number) => {
  1180. // setStorageSpeed(state.examSongId, speed);
  1181. state.speed = speed;
  1182. // 当前的音符
  1183. // const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.section[0] : state.times[state.activeNoteIndex];
  1184. const currentItem: any = state.times[state.activeNoteIndex];
  1185. state.basePlayRate = currentItem?.measureSpeed ? state.speed / currentItem.measureSpeed : state.speed / state.originSpeed;
  1186. const actualRate = state.originAudioPlayRate * state.basePlayRate;
  1187. console.log('速度设置',speed,'小节计算的倍率',state.basePlayRate,'实际播放倍率',actualRate)
  1188. };
  1189. /** 清除选段状态 */
  1190. export const clearSelection = () => {
  1191. state.sectionStatus = false;
  1192. state.section = [];
  1193. closeToast();
  1194. };
  1195. /** 开启选段 */
  1196. export const handleChangeSection = () => {
  1197. // 如果开启了选段,再次点击取消选段
  1198. if (state.sectionStatus) {
  1199. togglePlay("paused");
  1200. clearSelection();
  1201. // 重置速度和播放倍率
  1202. resetBaseRate(state.activeNoteIndex);
  1203. //skipNotePlay(0, true); 取消选段的时候 不跳回开头
  1204. state.sectionFirst = null;
  1205. // IOS18.1.1浏览器渲染更新有问题,需要手动更新一下
  1206. const selectionDom = document.getElementById('selectionBox')
  1207. if (selectionDom) {
  1208. selectionDom.style.display = 'none';
  1209. requestAnimationFrame(() => {
  1210. selectionDom.style.display = 'block';
  1211. })
  1212. }
  1213. return;
  1214. }
  1215. state.sectionStatus = true;
  1216. // 开启
  1217. if (state.sectionStatus) {
  1218. togglePlay("paused");
  1219. }
  1220. showToast({
  1221. message: "请选择开始小节",
  1222. duration: 0,
  1223. position: "top",
  1224. className: "selectionToast",
  1225. });
  1226. };
  1227. // 重置设置
  1228. export const resetSettings = () => {
  1229. // 切换模式,清除选段
  1230. metronomeData.cursorMode = state.modeType === 'follow' ? 1 : 2;
  1231. state.noSavePopShow = true;
  1232. metronomeData.activeIndex = null;
  1233. clearSelection();
  1234. skipNotePlay(0, true);
  1235. resetBaseRate();
  1236. resetCursorPosition();
  1237. // midi 重置播放进度
  1238. if (state.isAppPlay) {
  1239. audioData.progress = 0;
  1240. }
  1241. showToast({
  1242. message: "已将所有参数重置到默认状态",
  1243. position: "top",
  1244. });
  1245. };
  1246. /** 效验并格式化选段小节 */
  1247. const formateSelectMearure = (_list: any[]): any[] => {
  1248. if (!_list.length) return [];
  1249. const list = _list.sort((a, b) => a.time - b.time);
  1250. const startXml = list[0]?.measureOpenIndex;
  1251. const endXml = list.last()?.measureOpenIndex;
  1252. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  1253. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  1254. // 没有找到选段小节
  1255. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  1256. clearSelection();
  1257. return [];
  1258. }
  1259. list[0] = selectStartMeasure[0];
  1260. list[1] = selectEndMeasure.last();
  1261. let startItemINdex = list[0].i;
  1262. // 开启预备拍
  1263. if (state.isOpenPrepare) {
  1264. const startXmlIndex = list[0].MeasureNumberXML;
  1265. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  1266. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  1267. }
  1268. skipNotePlay(startItemINdex, startItemINdex === 0);
  1269. return list;
  1270. };
  1271. /** 选择选段 */
  1272. export const handleSelection = (item: any) => {
  1273. if (!state.sectionStatus || state.section.length > 1) return;
  1274. if (state.section.length !== 2 && item) {
  1275. state.section.push(item);
  1276. if (state.section.length === 2) {
  1277. setSection(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  1278. //state.section = formateSelectMearure(state.section);
  1279. closeToast();
  1280. resetCursorPosition();
  1281. }
  1282. }
  1283. if (state.section.length === 1) {
  1284. showToast({
  1285. message: "请选择结束小节",
  1286. duration: 0,
  1287. position: "top",
  1288. className: "selectionToast",
  1289. });
  1290. }
  1291. };
  1292. /** 阶段练习、阶段评测设置选段小节 */
  1293. export const setSection = (start: number, end: number, userSpeed?: number) => {
  1294. const startNotes = state.times.filter(
  1295. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  1296. )
  1297. const endNotes = state.times.filter(
  1298. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  1299. )
  1300. state.userChooseEndIndex = end
  1301. const lastEndId = endNotes[endNotes.length - 1].noteId
  1302. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  1303. // 是否符合重播规则
  1304. const canRepeatInfo = verifyCanRepeat(start, end)
  1305. console.log('能否重播', canRepeatInfo)
  1306. const isCanRepeat = canRepeatInfo.canRepeat
  1307. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1308. /**
  1309. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1310. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  1311. * TODO:通过vf-volta判断是否是跳房子
  1312. */
  1313. let isSkipVolta = false; // 结束小节是否是跳房子小节
  1314. if (lastEndNotes.length === 1) {
  1315. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  1316. }
  1317. let currentEndNum: number = end
  1318. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  1319. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  1320. currentEndNum = currentEndNum - 1
  1321. const newEndNotes = state.times.filter(
  1322. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  1323. )
  1324. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  1325. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  1326. }
  1327. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  1328. const startNote = startNotes[0]
  1329. // const endNote = endNotes[endNotes.length - 1]
  1330. const endNote = lastEndNotes[endIdx]
  1331. if (startNote && endNote) {
  1332. state.isSelectMeasureMode = true;
  1333. // 设置小节
  1334. hanldeDirectSelection([startNote, endNote]);
  1335. // 评测作业,练习作业的场景,需要用老师布置的速度,设置播放速度
  1336. if (userSpeed) {
  1337. handleSetSpeed(userSpeed);
  1338. }
  1339. }
  1340. }
  1341. /** 直接设置选段 */
  1342. export const hanldeDirectSelection = (list: any[]) => {
  1343. if (!Array.isArray(list) || list.length !== 2) return;
  1344. state.sectionStatus = true;
  1345. metronomeData.activeIndex = null;
  1346. setTimeout(() => {
  1347. state.section = formateSelectMearure(list);
  1348. // 选段完成后,需要根据预报小节的速度,设置右下角显示的速度
  1349. const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
  1350. if (currentItem.measureSpeed && query.workRecord === undefined && query.evaluatingRecord === undefined) {
  1351. handleSetSpeed(currentItem.measureSpeed);
  1352. }
  1353. console.log('选段小节', state.section)
  1354. }, 0);
  1355. };
  1356. let offsetTop = 0, musicScrollTop = 0;
  1357. /**
  1358. * 窗口内滚动到音符的区域
  1359. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  1360. * @returns void
  1361. */
  1362. export const scrollViewNote = (resetTop?: boolean) => {
  1363. // const cursorElement = document.getElementById("cursorImg-0")!;
  1364. if (state.isSingleLine) {
  1365. return;
  1366. }
  1367. const noteId = state.times[state.activeNoteIndex].id;
  1368. // if (!noteId) {
  1369. // return;
  1370. // }
  1371. const domId = "vf" + noteId;
  1372. // 合并休止小节没有音符,取小节的位置,否则取音符指针位置
  1373. const cursorElement: any = !noteId && state.times[state.activeNoteIndex]?.totalMultipleRestMeasures ? document.querySelector(`.measureIndex_${state.activeMeasureIndex}`) : document.querySelector(`[data-vf=${domId}]`)?.parentElement;
  1374. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  1375. if (!state.headTopHeight) {
  1376. state.headTopHeight = document.querySelector('.headHeight')?.getBoundingClientRect()?.height || 100;
  1377. }
  1378. // console.log('滑动',musicAndSelection?.scrollTop, musicScrollTop)
  1379. if (!cursorElement || !musicAndSelection) {
  1380. return
  1381. }
  1382. if (Math.abs(musicAndSelection?.scrollTop - musicScrollTop) > 30) {
  1383. // 手动滑动谱面,重新播放需要滚动到对应位置
  1384. } else {
  1385. if (offsetTop === cursorElement.offsetTop || Math.abs(offsetTop - cursorElement.offsetTop) < 30) return;
  1386. }
  1387. offsetTop = cursorElement.offsetTop;
  1388. if (offsetTop > (state.headTopHeight + 30)) {
  1389. musicScrollTop = (offsetTop - state.headTopHeight - 30) * state.musicZoom
  1390. musicAndSelection.scrollTo({
  1391. top: (offsetTop - state.headTopHeight - 30) * state.musicZoom,
  1392. behavior: "auto",
  1393. });
  1394. } else {
  1395. musicScrollTop = 0
  1396. musicAndSelection.scrollTo({
  1397. top: 0,
  1398. behavior: "auto",
  1399. });
  1400. }
  1401. };
  1402. /** 检测是否是节奏练习 */
  1403. export const isRhythmicExercises = () => {
  1404. return state.examSongName.indexOf("节奏练习") > -1;
  1405. };
  1406. /** 重置状态 */
  1407. export const handleRessetState = () => {
  1408. // 切换模式,清除选段
  1409. state.noSavePopShow = true;
  1410. clearSelection();
  1411. skipNotePlay(0, true);
  1412. resetBaseRate();
  1413. // midi 重置播放进度
  1414. if (state.isAppPlay) {
  1415. audioData.progress = 0;
  1416. }
  1417. if (state.modeType === "evaluating") {
  1418. handleStartEvaluat();
  1419. } else if (state.modeType === "practise") {
  1420. togglePlay("paused", true);
  1421. } else if (state.modeType === "follow") {
  1422. toggleFollow(false);
  1423. }
  1424. };
  1425. export default state;
  1426. /** 初始化评测音频 */
  1427. export const evaluatCreateMusicPlayer = () => {
  1428. return api_createMusicPlayer({
  1429. musicSrc: state.accompany || state.music, // 曲谱音频url
  1430. // tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1431. tuneSrc: "https://oss.dayaedu.com/MECMP/1722593665681.mp3", //效音音频url
  1432. checkFrequence: 496,
  1433. });
  1434. };
  1435. /** 获取内容平台的接口详情并初始化state信息 */
  1436. export const getMusicDetail = async (id: string, type?: string, musicId?: string) => {
  1437. const res = await getMusicSheetDetail(id, type, musicId);
  1438. if (res?.code === 200) {
  1439. await getMusicInfo(res)
  1440. }
  1441. };
  1442. const getMusicInfo = async (res: any) => {
  1443. // 是否支持总谱
  1444. state.isScoreRender = res.data?.isScoreRender
  1445. // 是否默认显示总谱
  1446. state.defaultScoreRender = res.data?.defaultScoreRender
  1447. /* 获取声轨列表 */
  1448. let xmlString = await fetch(res.data.xmlFileUrl).then((response) => response.text());
  1449. xmlString = xmlAddPartName(xmlString);
  1450. downloadXmlStr.value = xmlString //给musice-score 赋值xmlString 以免加载2次
  1451. const tracks = xmlToTracks(xmlString) //获取声轨列表
  1452. // 是否显示节拍器 (管乐迷 默认显示节拍器)
  1453. //state.isMixBeat = res.data?.isMixBeat
  1454. /* 设置partIndex */
  1455. let partIndexs = query["part-index"] ? query["part-index"].split(",") : ["-1"] // -1为partIndex没有值的时候
  1456. // 如果传入的是part-name,需要将part-name转换成part-index
  1457. if (query["part-name"]) {
  1458. const partValue = decodeURIComponent(query["part-name"]) || ''
  1459. let nameIdx = tracks.findIndex((item: any) => item == partValue)
  1460. partIndexs = [nameIdx]
  1461. }
  1462. partIndexs = partIndexs.map((indexStr:string) => {
  1463. return parseInt(indexStr)
  1464. }).sort((a, b) => a - b);
  1465. let partIndex = partIndexs[0]
  1466. // 当partIndexs 大于1个的时候,代表用户自己选择了多个声部,用总谱渲染的逻辑
  1467. if(partIndexs.length > 1){
  1468. partIndex = 999
  1469. state.combinePartIndexs = partIndexs
  1470. }
  1471. // 如果是评测报告,会有默认的分轨index
  1472. if (state.isEvaluatReport) {
  1473. partIndex = state.partIndex;
  1474. }
  1475. // 布置作业 取作业的乐器id
  1476. let workRecordInstrumentId:undefined | string
  1477. // multiTracksSelection 返回为空,默认代表全部分轨
  1478. state.canSelectTracks = res.data.multiTracksSelection === "null" || res.data.multiTracksSelection === "" || res.data.multiTracksSelection === null ? [] : res.data.multiTracksSelection?.split(',');
  1479. state.canSelectTracks = state.canSelectTracks.map((item: any)=>item.trim())
  1480. // 如果是多个分轨合并显示的,需要记录下所选分轨的第一个分轨的名字,渲染计算音符位置的时候需要根据第一个分轨找到对应音符的位置
  1481. if (state.combinePartIndexs.length) {
  1482. (window as any).DYFirstTrackName = tracks[state.combinePartIndexs[0]] || '';
  1483. } else {
  1484. (window as any).DYFirstTrackName = '';
  1485. }
  1486. // 如果是作业模式,需要默认渲染当前学生声部对应的声轨,并且默认不显示总谱
  1487. if (state.isHomeWork && storeData.user?.instrumentId) {
  1488. const currentTrack = res.data.musicSheetSoundList.find((item: any) => item.musicalInstrumentId === storeData.user?.instrumentId)?.track;
  1489. if (currentTrack) {
  1490. partIndex = tracks.findIndex(item => item === currentTrack) || partIndex
  1491. state.defaultScoreRender = false
  1492. }
  1493. }
  1494. // 设置音源 track 为当前的声轨 index为当前的
  1495. const { track, index, musicalInstrumentId } = state.isSimplePage ? { track:tracks[0], index: state.partIndex, musicalInstrumentId: '' } : initMusicSource(res.data, tracks, partIndex, workRecordInstrumentId)
  1496. // 这里返回的track可能和实际的对不上,所以重新筛选一下
  1497. const realTrack = musicalInstrumentId && res.data?.musicalInstruments?.length ? res.data?.musicalInstruments.find((item: any) => item?.id == musicalInstrumentId)?.code?.split(',')?.[0] : '';
  1498. const musicInfo = {
  1499. ...res.data,
  1500. track: res.data.playMode === "MIDI" ? tracks[0] || '' : res.data.musicSheetType === 'CONCERT' ? track : realTrack
  1501. };
  1502. console.log("🚀 ~ musicInfo:", musicInfo);
  1503. setState(musicInfo, index);
  1504. };
  1505. //获取xml中的音轨数据
  1506. function xmlToTracks(xmlString: string) {
  1507. const xmlParse = new DOMParser().parseFromString(xmlString, "text/xml");
  1508. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1509. return partNames.reduce((arr: string[], item) => {
  1510. const textContent = item?.textContent?.trim()
  1511. if (textContent?.toLocaleLowerCase() === "common") {
  1512. (window as any).HasCommonTrack = true;
  1513. }
  1514. if (textContent?.trim()?.toLocaleLowerCase() !== "common" && textContent) {
  1515. arr.push(textContent)
  1516. }
  1517. return arr
  1518. }, []);
  1519. }
  1520. // 设置音源
  1521. function initMusicSource(data: any, tracks: string[], partIndex: number, workRecordInstrumentId?: string) {
  1522. let track:string,index:number, musicalInstrumentId: string
  1523. let instrumentId = workRecordInstrumentId || query.instrumentId || storeData.user?.instrumentId
  1524. // 打击乐特殊处理 当曲目乐器为2266(打击乐(键盘))和2267(小军鼓)时候,从打击乐分类下 进入的时候
  1525. if(["2266", "2267"].includes(data.musicalInstrumentIds)){
  1526. instrumentId = data.musicalInstrumentIds
  1527. }
  1528. state.instrumentId = instrumentId;
  1529. let { musicSheetType, isAllSubject, musicSheetSoundList, musicSheetAccompanimentList } = data
  1530. musicSheetSoundList || (musicSheetSoundList = [])
  1531. musicSheetAccompanimentList || (musicSheetAccompanimentList = [])
  1532. let musicObj, accompanyObj, fanSongObj, banSongObj
  1533. /* 独奏 */
  1534. if (musicSheetType === "SINGLE") {
  1535. accompanyObj = musicSheetAccompanimentList.find((item: any) => {
  1536. return item.audioPlayType === "PLAY"
  1537. })
  1538. // 如果specialInstrumentIds有多个,是打击乐的声部,打击乐声部可能有多个乐器id
  1539. if (storeData.user?.specialInstrumentIds?.length > 1) {
  1540. musicObj = musicSheetSoundList.find((item: any) => {
  1541. return isAllSubject ? item.audioPlayType === "PLAY" : (item.audioPlayType === "PLAY" && storeData.user?.specialInstrumentIds?.includes(item.musicalInstrumentId))
  1542. })
  1543. } else {
  1544. // 是否全声部(isAllSubject)为true 时候没有乐器只有一个原音(比如节奏练习,这个曲子全部乐器都支持);当前用户有乐器就匹配 不然取第一个原音
  1545. musicObj = musicSheetSoundList.find((item: any) => {
  1546. return isAllSubject ? item.audioPlayType === "PLAY" : (item.audioPlayType === "PLAY" && item.musicalInstrumentId == instrumentId)
  1547. })
  1548. }
  1549. // 当没有找到原音的时候,并且instrumentId没有值的时候,取默认第一个乐器
  1550. if(!musicObj && !instrumentId){
  1551. musicObj = musicSheetSoundList.find((item: any) => {
  1552. return item.audioPlayType === "PLAY"
  1553. })
  1554. }
  1555. fanSongObj = musicSheetSoundList.find((item: any) => {
  1556. return item.audioPlayType === "SING"
  1557. })
  1558. banSongObj = musicSheetAccompanimentList.find((item: any) => {
  1559. return item.audioPlayType === "SING"
  1560. })
  1561. track = musicObj?.track //没有原音的时候track为空 不显示指法
  1562. index = tracks.findIndex(item => {
  1563. return item === track
  1564. })
  1565. musicalInstrumentId = musicObj?.musicalInstrumentId
  1566. } else {
  1567. /* 合奏 */
  1568. // 支持总谱 并且当前是总谱。partIndex是999时候,或者默认是总谱并且partIndex为-1时候 -1就是partIndex没有值
  1569. if((state.isScoreRender && (partIndex===999 || (state.defaultScoreRender && partIndex===-1))) || state.combinePartIndexs.length > 1){
  1570. // 总谱渲染
  1571. state.isCombineRender = true
  1572. banSongObj = musicSheetAccompanimentList.find((item: any) => {
  1573. return item.audioPlayType === "SING"
  1574. })
  1575. // 总谱演唱模式是 范唱,取banSongObj 里面的scoreAudioFileUrl字段
  1576. // 先取scoreAudioFileUrl的值 如果 没有就是空
  1577. if(banSongObj){
  1578. fanSongObj = {
  1579. audioFileUrl: banSongObj.scoreAudioFileUrl,
  1580. audioBeatMixUrl: banSongObj.scoreAudioBeatMixUrl
  1581. }
  1582. }
  1583. // 总谱 需要播放各个声部的音频
  1584. if(state.combinePartIndexs.length) {
  1585. // 当选择多个分轨时候
  1586. state.combinePartIndexs.map( partI => {
  1587. const musicSheetSound = musicSheetSoundList.find((item:any)=>{
  1588. return item.track?.toLowerCase().trim() === tracks[partI]?.toLowerCase().trim()
  1589. })
  1590. musicSheetSound?.audioFileUrl && (audioData.combineMusics[partI] = musicSheetSound.audioFileUrl)
  1591. })
  1592. }else{
  1593. tracks.map((itemTrack:any, partI:number) => {
  1594. const musicSheetSound = musicSheetSoundList.find((item:any)=>{
  1595. return item.track?.toLowerCase().trim() === itemTrack?.toLowerCase().trim()
  1596. })
  1597. musicSheetSound?.audioFileUrl && (audioData.combineMusics[partI] = musicSheetSound.audioFileUrl)
  1598. })
  1599. }
  1600. // 总谱演奏模式是 伴奏
  1601. accompanyObj = musicSheetAccompanimentList.find((item: any) => {
  1602. return item.audioPlayType === "PLAY"
  1603. })
  1604. track = "总谱"
  1605. index = 999
  1606. musicalInstrumentId = ''
  1607. }else{
  1608. // 合奏只显示一个声轨 当为-1时候,取tracks中 后端勾选了的第一个值
  1609. track = partIndex === -1 ? tracks.find(value => state.canSelectTracks.includes(value))! : tracks[partIndex]
  1610. // 根据当前的声轨 取数据
  1611. musicObj = musicSheetSoundList.find((item: any) => {
  1612. return item.audioPlayType === "PLAY" && item.track === track
  1613. })
  1614. fanSongObj = musicSheetSoundList.find((item: any) => {
  1615. return item.audioPlayType === "SING" && item.track === track
  1616. })
  1617. banSongObj = musicSheetAccompanimentList.find((item: any) => {
  1618. return item.audioPlayType === "SING"
  1619. })
  1620. accompanyObj = musicSheetAccompanimentList.find((item: any) => {
  1621. return item.audioPlayType === "PLAY"
  1622. })
  1623. index = tracks.findIndex(item => {
  1624. return item === track
  1625. })
  1626. musicalInstrumentId = musicObj?.musicalInstrumentId
  1627. }
  1628. state.partListNames = tracks
  1629. }
  1630. /* 目前 管乐迷没有演唱模式 所以先排除掉演唱模式的数据 */
  1631. if(fanSongObj?.audioFileUrl || banSongObj?.audioFileUrl || fanSongObj?.solmizationFileUrl || fanSongObj?.femaleSolmizationFileUrl){
  1632. fanSongObj?.audioFileUrl && (fanSongObj.audioFileUrl = null)
  1633. banSongObj?.audioFileUrl && (banSongObj.audioFileUrl = null)
  1634. fanSongObj?.solmizationFileUrl && (fanSongObj.solmizationFileUrl = null)
  1635. fanSongObj?.femaleSolmizationFileUrl && (fanSongObj.femaleSolmizationFileUrl = null)
  1636. }
  1637. // 当没有任何曲目的时候报错
  1638. if (!musicObj?.audioFileUrl && !accompanyObj?.audioFileUrl && !fanSongObj?.audioFileUrl && !banSongObj?.audioFileUrl && !fanSongObj?.solmizationFileUrl && !fanSongObj?.femaleSolmizationFileUrl) {
  1639. state.noMusicSource = !data.midiFileUrl ? true : false // 没有音源文件
  1640. // 独奏的时候
  1641. if(musicSheetType === "SINGLE"){
  1642. // 并且是midi没有midi文件的时候
  1643. if(data.playMode === "MIDI" && !data.midiFileUrl) {
  1644. // 是预览的时候 不报错
  1645. if(!query.isPreView){
  1646. throw new Error("该曲目无任何音源");
  1647. }
  1648. }
  1649. }
  1650. }
  1651. Object.assign(state, {
  1652. music: musicObj?.audioFileUrl,
  1653. accompany: accompanyObj?.audioFileUrl,
  1654. fanSong: fanSongObj?.audioFileUrl,
  1655. banSong: banSongObj?.audioFileUrl,
  1656. })
  1657. // 如果没有男唱名
  1658. if(!fanSongObj?.solmizationFileUrl){
  1659. state.mingSong = fanSongObj?.femaleSolmizationFileUrl
  1660. }else{
  1661. state.mingSong = fanSongObj?.solmizationFileUrl
  1662. state.mingSongGirl = fanSongObj?.femaleSolmizationFileUrl
  1663. }
  1664. /* 目前 管乐迷没有用到 后台生成的节拍器 */
  1665. // 当使用节拍器的时候才加载节拍器音频
  1666. if(state.isMixBeat && false) {
  1667. Object.assign(state.beatSong, {
  1668. music: musicObj?.audioBeatMixUrl,
  1669. accompany: accompanyObj?.audioBeatMixUrl,
  1670. fanSong: fanSongObj?.audioBeatMixUrl,
  1671. banSong: banSongObj?.audioBeatMixUrl
  1672. })
  1673. // 如果没有男唱名
  1674. if(!fanSongObj?.solmizationBeatUrl){
  1675. state.beatSong.mingSong = fanSongObj?.femaleSolmizationBeatUrl
  1676. }else{
  1677. state.beatSong.mingSong = fanSongObj?.solmizationBeatUrl
  1678. state.beatSong.mingSongGirl = fanSongObj?.femaleSolmizationBeatUrl
  1679. }
  1680. }
  1681. return {
  1682. index,
  1683. track,
  1684. musicalInstrumentId
  1685. }
  1686. }
  1687. const setState = (data: any, index: number) => {
  1688. // 获取当前模式 声部切换用
  1689. const localStoragePlayType = localStorage.getItem("musicScorePlayType")
  1690. if(localStoragePlayType) {
  1691. localStorage.removeItem("musicScorePlayType")
  1692. const fields = localStoragePlayType.split(',')
  1693. state.playType = fields[0] as any
  1694. state.playSource = fields[1] as any
  1695. }
  1696. // 根据当前文件有没有 设置当前的播放模式
  1697. const playObj = {
  1698. "play_music":"music",
  1699. "play_background":"accompany",
  1700. "sing_music":"fanSong",
  1701. "sing_background":"banSong",
  1702. "sing_mingSong":"mingSong",
  1703. } as any
  1704. // 当前缓存 有值的时候 用这个,没有的时候 走筛选
  1705. // @ts-ignore
  1706. if(!state[playObj[`${state.playType}_${state.playSource}`]]){
  1707. if(state.playType === "play"){
  1708. if(state.music){
  1709. state.playSource = "music"
  1710. }else if(state.accompany){
  1711. state.playSource = "background"
  1712. }else{
  1713. if(state.fanSong){
  1714. state.playType = "sing"
  1715. state.playSource = "music"
  1716. }else if(state.banSong){
  1717. state.playType = "sing"
  1718. state.playSource = "background"
  1719. }else if(state.mingSong){
  1720. state.playType = "sing"
  1721. state.playSource = "mingSong"
  1722. }
  1723. }
  1724. }else{
  1725. if(state.fanSong){
  1726. state.playSource = "music"
  1727. }else if(state.banSong){
  1728. state.playSource = "background"
  1729. }else if(state.mingSong){
  1730. state.playSource = "mingSong"
  1731. }else{
  1732. if(state.music){
  1733. state.playType = "play"
  1734. state.playSource = "music"
  1735. }else if(state.accompany){
  1736. state.playType = "play"
  1737. state.playSource = "background"
  1738. }
  1739. }
  1740. }
  1741. }
  1742. state.appName = "COLEXIU";
  1743. state.detailId = data.bizId;
  1744. state.musicPrice = data.musicPrice || 0;
  1745. state.xmlUrl = data.xmlFileUrl;
  1746. // 曲子付费类型
  1747. state.paymentType = data.paymentType;
  1748. // 是否已经购买
  1749. state.musicBuyInfo = {
  1750. id: data.bizId,
  1751. musicPrice: data.musicPrice,
  1752. paymentType: data.paymentType,
  1753. buyed: data.buyed
  1754. }
  1755. state.partIndex = index >= 0 ? index : 0;
  1756. state.trackId = data.track;
  1757. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1758. // 声部code
  1759. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1760. // 打击乐列表查询用
  1761. state.specialPercussionFlag = data.specialPercussionFlag
  1762. state.musicalInstrumentIds = data.musicalInstrumentIds || ""
  1763. // 乐器code
  1764. // let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1765. /**
  1766. * 单曲,指法根据用户当前的乐器来显示,如果没有则取musicSheetSoundList第一个track
  1767. */
  1768. // const currentInstrumentId = query.instrumentId || storeData.user?.instrumentId;
  1769. // 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 || '';
  1770. // const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1771. // const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1772. // state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1773. // state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1774. state.categoriesId = data.musicCategoryId;
  1775. state.categoriesName = data.musicTagNames;
  1776. // state.enableEvaluation = data.isEvaluated ? true : false;
  1777. state.examSongId = data.bizId + "";
  1778. state.cbsExamSongId = data.id + "";
  1779. state.examSongName = data.name;
  1780. state.coverImg = data.musicCover ?? "";
  1781. // 如果是simple页面,只显示单轨
  1782. if (state.isSimplePage) {
  1783. state.isCombineRender = false;
  1784. }
  1785. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1786. // 解析扩展字段
  1787. if (data.extConfigJson) {
  1788. try {
  1789. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1790. } catch (error) {
  1791. console.error("解析扩展字段错误:", error);
  1792. }
  1793. }
  1794. state.gradualTimes = state.extConfigJson.gradualTimes;
  1795. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1796. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1797. // 是否开启节拍器
  1798. state.needTick = !!data.isPlayBeat
  1799. state.needSingTick = !!data.isPlaySingBeat
  1800. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1801. // 演奏模式是否播mp3节拍器
  1802. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1803. // 演唱模式是否播mp3节拍器
  1804. state.isSingOpenMetronome = data.isPlaySingBeat && !data.isUseSingSystemBeat ? true : false
  1805. state.isShowFingering = data.isShowFingering ? true : false;
  1806. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1807. state.isAppPlay = data.playMode === 'MIDI';
  1808. if (state.isAppPlay) {
  1809. state.isOpenMetronome = false
  1810. state.isSingOpenMetronome = false
  1811. }
  1812. state.midiUrl = data.midiFileUrl;
  1813. state.parentCategoriesId = data.musicTag;
  1814. state.musicSheetCategoriesId = data.musicCategoryId;
  1815. state.bizMusicCategoryId = data.bizMusicCategoryId
  1816. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1817. // 设置速度节拍
  1818. state.speedBeatUnit = data.speedBeatUnit || "1/4"
  1819. // 这里把后台设置的速度 转换为1/4拍的速度
  1820. state.originSpeed = state.speed = speedBeatTo({unit: data.speedBeatUnit || "1/4",speed: parseFloat(data.playSpeed) || 0}, `1/4`);
  1821. const track = data.code || data.track;
  1822. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1823. // 能否评测,根据当前声轨有无伴奏判断
  1824. if (state.isAppPlay) {
  1825. state.enableEvaluation = state.midiUrl ? true : false
  1826. } else {
  1827. state.enableEvaluation = state.accompany || state.music ? true : false
  1828. }
  1829. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1830. // 开启预备小节
  1831. state.isOpenPrepare = true;
  1832. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1833. state.extJianStyleConfigJson = data.extJianStyleConfigJson || {}
  1834. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1835. // 是否打击乐
  1836. /**
  1837. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1838. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1839. * 打击乐&节奏练习,没有跟练模式
  1840. */
  1841. // state.isPercussion = isRhythmicExercises();
  1842. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1843. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1844. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1845. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1846. // 设置指法
  1847. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1848. /**
  1849. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1850. * 获取指法code
  1851. */
  1852. // const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1853. const code = matchVoicePart(state.trackId, "CONCERT")
  1854. state.fingeringInfo = subjectFingering(code);
  1855. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1856. state.musicalCodeId = state.fingeringInfo?.id || 0
  1857. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1858. ; (window as any).DYSubjectId = state.musicalCodeId
  1859. // 开启自定义每行显示的小节数
  1860. ; (window as any).customSectionAmount = true
  1861. // 标识是课堂乐器,用于移调时进行区分处理
  1862. ; (window as any).DYProjectName = 'musicScore';
  1863. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1864. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1865. state.setting.displayFingering = false
  1866. }
  1867. // 如果是PC端,放大曲谱
  1868. state.platform = query.platform?.toLocaleUpperCase() || "";
  1869. if (state.platform === IPlatform.PC || state.systemType === 'web') {
  1870. // pc端,谱面默认初始大小设置为1.5
  1871. if (state.platform === IPlatform.PC) {
  1872. state.zoom = 1.5;
  1873. }
  1874. if (query.zoom <= 1) {
  1875. state.zoom = query.zoom ? Number(query.zoom) : state.zoom;
  1876. } else {
  1877. state.zoom = localStorage.getItem('scoreZoom') ? Number(localStorage.getItem('scoreZoom')) : state.zoom
  1878. }
  1879. }
  1880. if (storeData.isApp && !state.isPreView) {
  1881. state.zoom = localStorage.getItem('scoreZoom') ? Number(localStorage.getItem('scoreZoom')) : state.zoom
  1882. }
  1883. // 详情预览页面,曲谱比例
  1884. if (state.isPreView) {
  1885. state.zoom = query.zoom ? Number(query.zoom) : state.zoom;
  1886. }
  1887. // 评测报告取默认谱面大小
  1888. if (state.isEvaluatReport) {
  1889. state.zoom = 0.8
  1890. }
  1891. // 非APP打开的页面,禁止评测
  1892. if (!storeData.isApp) {
  1893. // state.enableEvaluation = false;
  1894. }
  1895. /**
  1896. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1897. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1898. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1899. *
  1900. */
  1901. // let pitchTrack = null
  1902. // if (state.isConcert) {
  1903. // musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1904. // pitchTrack = data.musicalInstruments?.find((item: any) => item.code?.split(',')[0] === musicalCode)
  1905. // } else {
  1906. // pitchTrack = data.musicalInstruments?.find((item: any) => item.code?.split(',')[0] === musicalCode)
  1907. // }
  1908. let musicalRenderType = ''
  1909. // if (pitchTrack?.defaultScore) {
  1910. // musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1911. // }
  1912. // state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1913. /**
  1914. * 2024.7.30,使用新的字段
  1915. * 谱面类型,scoreType
  1916. * STAVE("五线谱"),JIAN("固定调"),FIRST("首调"),
  1917. */
  1918. musicalRenderType = data.scoreType === 'STAVE' ? 'staff' : data.scoreType === 'JIAN' ? 'fixedTone' : data.scoreType === 'FIRST' ? '' : 'firstTone';
  1919. if (!state.isEvaluatReport) {
  1920. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1921. }
  1922. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1923. /**
  1924. * TODO:摇篮曲特殊处理
  1925. */
  1926. if (['1788501975122489346', '1788502467554750466', '1789839575249596417'].includes(state.cbsExamSongId)) {
  1927. if (state.musicRenderType === 'fixedTone') {
  1928. state.musicRenderType = EnumMusicRenderType.firstTone;
  1929. }
  1930. }
  1931. /**
  1932. * 2024.7.30,使用新的字段
  1933. * 能否转谱,isConvertibleScore
  1934. * true:能转谱,false:不能转谱
  1935. * 额外的逻辑:后台设置不能转谱时,如果默认谱面不是五线谱,需要显示转谱按钮,但是只能转首调和固定调
  1936. */
  1937. // state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1938. state.enableNotation = data.isConvertibleScore
  1939. state.specialShowNotation = !data.isConvertibleScore && data.scoreType !== 'STAVE';
  1940. console.log("state对象", state);
  1941. // 评测基准频率
  1942. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1943. state.baseFrequency = Number(state.baseFrequency)
  1944. // 用户上次的频率和基准频率误差超过10,则重置
  1945. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1946. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1947. } else {
  1948. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1949. }
  1950. state.playBtnDirection = query.imagePos === 'left' ? 'left' : 'right';
  1951. state.isAttendClass = (query.imagePos === 'left' || query.imagePos === 'right') ? true : false;
  1952. };
  1953. // 多分轨合并显示标示
  1954. const setCustom = (trackNum?: number) => {
  1955. if (trackNum || state.extConfigJson.multitrack) {
  1956. state.multitrack = trackNum || 0
  1957. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1958. }
  1959. };
  1960. /** 跟练模式播放节拍器(叮咚) */
  1961. export const followBeatPaly = () => {
  1962. let metroTimer: any = null;
  1963. if (!followData.start) {
  1964. clearTimeout(metroTimer)
  1965. metroTimer = null
  1966. return;
  1967. }
  1968. const time = state.measureTime * 1000 / metronomeData.totalNumerator / state.basePlayRate;
  1969. requestAnimationFrame(() => {
  1970. const endTime = Date.now();
  1971. if (endTime - state.beatStartTime < time) {
  1972. followBeatPaly();
  1973. } else {
  1974. // metroTimer = setTimeout(() => {
  1975. // metronomeData.metro?.simulatePlayAudio()
  1976. // startTime = Date.now();
  1977. // followBeatPaly();
  1978. // }, time);
  1979. metronomeData.metro?.simulatePlayAudio()
  1980. state.beatStartTime = Date.now();
  1981. followBeatPaly();
  1982. }
  1983. });
  1984. };
  1985. // 音符添加bbox
  1986. export const addNoteBBox = (list: any[]) => {
  1987. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  1988. x: 0,
  1989. y: 0,
  1990. };
  1991. const parentLeft = musicContainer.x || 0;
  1992. let voicesBBox: any = null;
  1993. for (let i = 0; i < list.length; i++) {
  1994. const note = list[i];
  1995. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1996. /**
  1997. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1998. */
  1999. let bbox: any = null;
  2000. if (svgElement?.attrs.id) {
  2001. // @ts-ignore
  2002. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  2003. const noteBbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBoundingClientRect?.() || { x: 0, width: 0 };
  2004. bbox = {
  2005. left: noteBbox.x - parentLeft - noteBbox.width / 4, // 用于简谱模式,跳动音符时,设置光标的位置(五线谱:osmd自动设置光标位置,简谱:需要手动设置光标位置)
  2006. x: bbox?.x * state.zoom,
  2007. y: bbox?.y * state.zoom,
  2008. width: bbox?.width * state.zoom,
  2009. height: bbox?.height * state.zoom,
  2010. }
  2011. } else {
  2012. // @ts-ignore
  2013. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  2014. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  2015. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  2016. currentVoicesBBox = voicesBBox;
  2017. }
  2018. let nextIndex = i + 1;
  2019. while (!list[nextIndex]?.id && nextIndex < list.length) {
  2020. nextIndex += 1;
  2021. }
  2022. // 休止小节的开头和下一个音符之间的间距
  2023. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  2024. if (list[nextIndex]?.id) {
  2025. // @ts-ignore
  2026. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  2027. }
  2028. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  2029. bbox = currentVoicesBBox ? {
  2030. bottom: currentVoicesBBox.bottom,
  2031. height: 30,
  2032. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  2033. right: currentVoicesBBox.y,
  2034. top: currentVoicesBBox.top,
  2035. width: 1,
  2036. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  2037. y: currentVoicesBBox.y,
  2038. svgBodyLeft: svgBodyBBox?.x,
  2039. } : null;
  2040. voicesBBox = currentVoicesBBox;
  2041. }
  2042. note.bbox = bbox;
  2043. }
  2044. }
  2045. // 给歌词和音符添加动态颜色
  2046. let prevActiveNoteIndex = -1 // 上一个激活的
  2047. export const fillWordColor = () => {
  2048. // console.log('当前音符',state.activeNoteIndex,prevActiveNoteIndex)
  2049. if(prevActiveNoteIndex !== -1) {
  2050. const prevActiveNoteId = state.times[prevActiveNoteIndex]?.svgElement?.attrs?.id
  2051. const svgEl = document.getElementById(`vf-${prevActiveNoteId}`)
  2052. const stemEl = document.getElementById(`vf-${prevActiveNoteId}-stem`)
  2053. const stemLine = document.getElementById(`vf-${prevActiveNoteId}-lines`)
  2054. svgEl?.classList.remove('noteActive')
  2055. stemEl?.classList.remove('noteActive')
  2056. // stemLine?.classList.remove('noteActive')
  2057. svgEl?.parentElement?.classList.remove('voiceActive')
  2058. const si = state.times[prevActiveNoteIndex].si || 0;
  2059. svgEl?.parentElement?.querySelectorAll('rect')?.forEach((item: any) => {
  2060. item?.classList.remove('rectActive');
  2061. })
  2062. // svgEl?.parentElement?.querySelectorAll('rect')?.[si]?.classList.remove('rectActive');
  2063. }
  2064. const activeNoteId = state.times[state.activeNoteIndex]?.svgElement?.attrs?.id
  2065. const svgEl = document.getElementById(`vf-${activeNoteId}`)
  2066. const stemEl = document.getElementById(`vf-${activeNoteId}-stem`)
  2067. const stemLine = document.getElementById(`vf-${activeNoteId}-lines`)
  2068. svgEl?.classList.add('noteActive')
  2069. stemEl?.classList.add('noteActive')
  2070. // stemLine?.classList.add('noteActive')
  2071. // 如果是简谱、固定调,需要把音符后面跟着的"-"也添加颜色
  2072. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  2073. // const parentVoice = svgEl?.parentElement;
  2074. // 简谱模式下,二分音符和全音符才显示音符右侧的"-"
  2075. if (state.times[state.activeNoteIndex].noteElement?.length?.realValue >= 0.5) {
  2076. // 如果是二分音符,只亮该音符后面那个"-",本小节其它的"-"不亮
  2077. if (state.times[state.activeNoteIndex].noteElement?.length?.realValue === 0.5) {
  2078. const si = state.times[state.activeNoteIndex].si || 0;
  2079. const halfNotes = state.times[state.activeNoteIndex].measures.filter((item: any) => item?.noteElement?.length?.realValue === 0.5) || [];
  2080. const sIdx = halfNotes?.findIndex((item: any) => item?.noteElement === state.times[state.activeNoteIndex]?.noteElement);
  2081. const filterRects = svgEl?.parentElement?.querySelectorAll('rect')?.length ? Array.from(svgEl?.parentElement?.querySelectorAll('rect')).filter(item => item.parentElement === svgEl?.parentElement) : [];
  2082. filterRects?.[sIdx]?.classList.add('rectActive');
  2083. } else {
  2084. svgEl?.parentElement?.classList.add('voiceActive');
  2085. }
  2086. }
  2087. }
  2088. prevActiveNoteIndex = state.activeNoteIndex
  2089. // 给当前匹配到的歌词添加颜色
  2090. const currentNote = state.times[state.activeNoteIndex];
  2091. const lyrics: SVGAElement[] = Array.from(document.querySelectorAll(".vf-lyric"));
  2092. lyrics.forEach((lyric) => {
  2093. lyric?.classList.remove('lyricActive')
  2094. })
  2095. const currentLyrics: SVGAElement[] = Array.from(document.querySelectorAll(`.lyric${currentNote?.noteId}`));
  2096. currentLyrics.forEach((lyric, index) => {
  2097. const lyricIndex = lyric.getAttribute('lyricIndex');
  2098. // bug:#10942,如果需要反复唱的小节,只有一遍歌词,反复唱的时候,歌词都需要高亮
  2099. const onlyOneLyric = currentNote.measures?.every((item: any) => item?.formatLyricsEntries?.length <= 1);
  2100. if ((index === currentNote.repeatIdx && currentNote.repeatIdx + 1 == lyricIndex) || (currentNote.repeatIdx != index && !onlyOneLyric && currentNote.repeatIdx + 1 == lyricIndex) || (currentNote.repeatIdx > 0 && currentNote.formatLyricsEntries?.length === 1 && onlyOneLyric)) {
  2101. lyric?.classList.add('lyricActive')
  2102. }
  2103. // bug: #11189,兼容处理需要唱4遍,但是只打了2遍歌词的情况,1、3唱一样的歌词,2、4唱一样的歌词
  2104. if ( currentNote.formatLyricsEntries.length == 2 && currentNote.repeatIdx >= 2 && index === (currentNote.repeatIdx - 2) ) {
  2105. lyric?.classList.add('lyricActive')
  2106. }
  2107. // if ((index === currentNote.repeatIdx && currentNote.repeatIdx + 1 == lyricIndex)) {
  2108. // lyric?.classList.add('lyricActive')
  2109. // }
  2110. })
  2111. }
  2112. /** 跳动svgdom */
  2113. export const moveSvgDom = (skipNote?: boolean) => {
  2114. /**
  2115. * 计算需要移动的距离
  2116. * 当前选中的音符和第一个音符之间的间距
  2117. */
  2118. if (skipNote) {
  2119. // 点击 清空translateXNum
  2120. smoothAnimationState.translateXNum = 0
  2121. moveTranslateXNum(0)
  2122. // 移动小鸟的位置
  2123. moveSmoothAnimation(0, state.activeNoteIndex, false)
  2124. // 移动谱面当当前音符的位置
  2125. const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x
  2126. smoothAnimationState.osdmScrollDom!.scrollTo({
  2127. left: distance,
  2128. behavior: "smooth",
  2129. });
  2130. }
  2131. }
  2132. // 暂停的时候 恢复一行谱偏移位置信息
  2133. watch(
  2134. () => state.playState,
  2135. () => {
  2136. if (state.isSingleLine) {
  2137. // 当在播放中暂停 执行这个方法
  2138. if (!state.playEnd && state.playState === "paused") {
  2139. moveTranslateXNum(0)
  2140. // 因为safari浏览器scrollWidth的值一直变化,scrollLeft + smoothAnimationState.translateXNum 为最大宽度的时候,实际上scrollLeft滚不到最大宽度,所以在下一帧处理滚动,能滚动到最大滚动位置
  2141. requestAnimationFrame(() => {
  2142. const scrollLeft = smoothAnimationState.osdmScrollDom!.scrollLeft
  2143. smoothAnimationState.osdmScrollDom!.scrollLeft = scrollLeft + smoothAnimationState.translateXNum
  2144. smoothAnimationState.translateXNum = 0
  2145. });
  2146. }
  2147. }
  2148. }
  2149. )
  2150. /* 根据当前的小节获取前面有多少需要去除的合并小节 */
  2151. function getNeedReduceMultipleRestNum(currMeasureIndex: number) {
  2152. let needReduceMultipleRestNum = 0;
  2153. for (let noteIndex = 0; noteIndex < state.times.length; noteIndex++) {
  2154. const note = state.times[noteIndex];
  2155. if (note.MeasureNumberXML > currMeasureIndex) {
  2156. break;
  2157. }
  2158. if (note.multipleRestMeasures && note.multipleRestMeasures > 1) {
  2159. needReduceMultipleRestNum += 1;
  2160. }
  2161. }
  2162. return needReduceMultipleRestNum
  2163. }
  2164. watch(
  2165. () => state.activeMeasureIndex,
  2166. () => {
  2167. // 监听音符小节的变化,取对应的小节速度图片
  2168. const currentNote = state.times[state.activeNoteIndex]
  2169. state.speedIcon = unitImgs[currentNote.speedBeatUnit]
  2170. // 需要减去的合并小节数
  2171. // const needReduceMultipleRestNum = getNeedReduceMultipleRestNum(state.activeMeasureIndex)
  2172. // const matchMeasureNum = state.activeMeasureIndex - needReduceMultipleRestNum - 1
  2173. // console.log('选中的小节',matchMeasureNum,'需要减去的小节',needReduceMultipleRestNum,'当前的小节',state.activeMeasureIndex)
  2174. state.vfmeasures.forEach((item: any, idx: number) => {
  2175. const dataNum = item.getAttribute('data-num') // 值可能为字符串类型的undefined
  2176. let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
  2177. let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
  2178. // 当有换行小节,下个小节的nextDataNum是undefined,所以这里需要往后找一个
  2179. if(!(nextDataNum && nextDataNum !== "undefined")){
  2180. nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
  2181. }
  2182. const nextMeasureNum = Number(nextDataNum)
  2183. // 当measureNum 为undefined 则是下一个小节的换行小节,所以这里等于下一个小节
  2184. if(measureNum === -1) {
  2185. measureNum = nextMeasureNum
  2186. }
  2187. if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex))) {
  2188. item.querySelector('.vf-custom-bg')?.setAttribute("fill", state.isSimplePage ? "rgba(45, 199, 170, 0.3)" : "rgba(45, 199, 170, 0.2)")
  2189. // 预备小节
  2190. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML && state.section.length === 2){
  2191. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255, 193, 48, 0.15)")
  2192. }
  2193. // 如果是选段,超出选段时,不添加背景色
  2194. if (state.section.length === 2 && state.activeMeasureIndex > state.section[1].MeasureNumberXML) {
  2195. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "transparent")
  2196. }
  2197. } else {
  2198. // 有选段只清除选段处的
  2199. if (state.section.length === 2) {
  2200. // 把中间置灰
  2201. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  2202. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  2203. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  2204. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  2205. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  2206. }
  2207. if(measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML){
  2208. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(45, 199, 170, 0.15)")
  2209. }
  2210. // 预备小节
  2211. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
  2212. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255, 193, 48, 0.15)")
  2213. }
  2214. } else {
  2215. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "transparent")
  2216. }
  2217. }
  2218. })
  2219. }
  2220. );
  2221. watch(
  2222. () => state.section,
  2223. () => {
  2224. if (state.section.length === 2) {
  2225. // 把前面和 后面置灰
  2226. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  2227. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  2228. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  2229. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  2230. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  2231. }
  2232. state.vfmeasures.forEach((item: any, idx: number) => {
  2233. const dataNum = item.getAttribute('data-num') // 值可能为字符串类型的undefined
  2234. let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
  2235. let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
  2236. // 当有换行小节,下个小节的nextDataNum是undefined,所以这里需要往后找一个
  2237. if(!(nextDataNum && nextDataNum !== "undefined")){
  2238. nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
  2239. }
  2240. const nextMeasureNum = Number(nextDataNum)
  2241. // 当measureNum 为undefined 则是下一个小节的换行小节,所以这里等于下一个小节
  2242. if(measureNum === -1) {
  2243. measureNum = nextMeasureNum
  2244. }
  2245. // 小于选中置灰
  2246. if (measureNum < leftMeasureNumberXML) {
  2247. item.querySelector('.vf-custom-bg')?.setAttribute("fill", 'transparent')
  2248. }
  2249. // 大于选中置灰
  2250. if(measureNum > rightMeasureNumberXML){
  2251. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "transparent")
  2252. }
  2253. if (measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML) {
  2254. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(45, 199, 170, 0.15)")
  2255. }
  2256. // 预备小节
  2257. if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
  2258. item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255, 193, 48, 0.15)")
  2259. }
  2260. })
  2261. }else{
  2262. // 恢复选段前
  2263. state.vfmeasures.forEach((item: any, idx: number) => {
  2264. const dataNum = item.getAttribute('data-num') // 值可能为字符串类型的undefined
  2265. let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
  2266. let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
  2267. // 当有换行小节,下个小节的nextDataNum是undefined,所以这里需要往后找一个
  2268. if(!(nextDataNum && nextDataNum !== "undefined")){
  2269. nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
  2270. }
  2271. const nextMeasureNum = Number(nextDataNum)
  2272. // 当measureNum 为undefined 则是下一个小节的换行小节,所以这里等于下一个小节
  2273. if(measureNum === -1) {
  2274. measureNum = nextMeasureNum
  2275. }
  2276. if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex)) ) {
  2277. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(45, 199, 170, 0.15)")
  2278. } else {
  2279. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "transparent")
  2280. }
  2281. })
  2282. }
  2283. }
  2284. )
  2285. // 后台编辑谱面模式,切换谱面时,如果有操作没有保存,需要给出提示
  2286. export const checkMoveNoSave = async () => {
  2287. return new Promise((resolve, reject) => {
  2288. if (query.isMove) {
  2289. if (moveData.open && undoData.undoList.length) {
  2290. showConfirmDialog({
  2291. className: "noSaveModal",
  2292. title: "温馨提示",
  2293. message: "您有新的修改还未保存,切换谱面后本次编辑的内容将不会保存",
  2294. }).then(() => {
  2295. moveData.open = false
  2296. resolve(true)
  2297. }).catch(() => {
  2298. return;
  2299. });
  2300. } else {
  2301. moveData.open = false
  2302. undoData.undoList = []
  2303. resolve(true)
  2304. }
  2305. } else {
  2306. resolve(true)
  2307. }
  2308. });
  2309. }
  2310. /** 刷新谱面 */
  2311. export const refreshMusicSvg = () => {
  2312. moveData.noteCoords = []
  2313. moveData.modelList = []
  2314. clearSelection();
  2315. resetBaseRate();
  2316. state.activeMeasureIndex = -1;
  2317. metronomeData.activeIndex = null;
  2318. if (query.workRecord || query.evaluatingRecord) {
  2319. state.workSectionNeedReset = true;
  2320. }
  2321. // 销毁旋律线
  2322. destroySmoothAnimation()
  2323. musicScoreRef.value?.refreshMusicScore()
  2324. }
  2325. // 指法改变显示的时候 osdmScrollDomWith 宽度会变化 所以指法改变的时候这个宽度重新计算
  2326. watch(
  2327. () => state.setting.displayFingering,
  2328. () => {
  2329. // 有字符 并且是竖向指法 并且是一行谱
  2330. if(state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && state.isSingleLine){
  2331. nextTick(() => {
  2332. calcClientWidth()
  2333. })
  2334. }
  2335. // 如果有指法,并且是竖向指法时,切换指法时,谱面宽度变化,需要重新渲染谱面
  2336. if (state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && !state.isSingleLine) {
  2337. headTopData.settingMode = false;
  2338. refreshMusicSvg();
  2339. }
  2340. }
  2341. )
  2342. // 完成拖动弹窗引导页
  2343. export const handleGuide = async () => {
  2344. const guideInfoStore = localStorage.getItem('guideInfo') ? JSON.parse(localStorage.getItem('guideInfo')) : {};
  2345. guideInfoStore.teacherDrag = true;
  2346. try {
  2347. localStorage.setItem("guideInfo", JSON.stringify(guideInfoStore));
  2348. state.guideInfo = guideInfoStore
  2349. } catch (e) {
  2350. console.log(e);
  2351. }
  2352. };
  2353. // 手动设置音符指针位置
  2354. export const resetCursorPosition = () => {
  2355. nextTick(() => {
  2356. if (metronomeData.cursorMode === 1) {
  2357. const currentActives: HTMLElement[] = Array.from(document.querySelectorAll(".dotActive"));
  2358. currentActives.forEach((currentActive) => {
  2359. currentActive?.classList.remove("dotActive");
  2360. })
  2361. // const currentDot = document.querySelector(`.noteIndex_${state.activeNoteIndex}`)
  2362. const noteId = state.times[state.activeNoteIndex].id;
  2363. const domId = "vf" + noteId;
  2364. const currentDot = document.querySelector(`[data-vf=${domId}]`)?.parentElement
  2365. currentDot?.classList.add('dotActive')
  2366. } else {
  2367. const currentActives: HTMLElement[] = Array.from(document.querySelectorAll(".dotActive"));
  2368. currentActives.forEach((currentActive) => {
  2369. currentActive?.classList.remove("dotActive");
  2370. })
  2371. }
  2372. // metronomeData?.metro?.findMetronomePosition(0);
  2373. })
  2374. }
  2375. watch(
  2376. () => state.activeNoteIndex,
  2377. () => {
  2378. resetCursorPosition();
  2379. }
  2380. );