state.ts 83 KB

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