state.ts 87 KB

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