state.ts 90 KB

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