state.ts 85 KB

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