state.ts 92 KB

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