state.ts 92 KB

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