state.ts 85 KB

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