state.ts 91 KB

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