state.ts 80 KB

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