state.ts 91 KB

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