state.ts 86 KB

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