state.ts 88 KB

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