state.ts 89 KB

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