state.ts 92 KB

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