state.ts 85 KB

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