state.ts 89 KB

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