state.ts 82 KB

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