12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135 |
- import { closeToast, showToast, showConfirmDialog } from "vant";
- import { nextTick, reactive, watch } from "vue";
- import { OpenSheetMusicDisplay } from "../osmd-extended/src";
- import { metronomeData } from "./helpers/metronome";
- import { GradualNote, GradualTimes, GradualVersion } from "./type";
- import { handleEndEvaluat, handleStartEvaluat } from "./view/evaluating";
- import { IFingering, mappingVoicePart, subjectFingering, matchVoicePart } from "/src/view/fingering/fingering-config";
- import { handleStartTick, closeTick } from "./view/tick";
- import { audioListStart, getAudioCurrentTime, getAudioDuration, setAudioCurrentTime, setAudioPlaybackRate, audioData } from "./view/audio-list";
- import { toggleFollow } from "./view/follow-practice";
- import { browser, setStorageSpeed, setGlobalData } from "./utils";
- import { api_cloudGetMediaStatus, api_createMusicPlayer, api_cloudChangeSpeed, api_cloudSuspend, api_cloudSetCurrentTime, api_cloudDestroy } from "./helpers/communication";
- import { verifyCanRepeat, getDuration, xmlAddPartName } from "./helpers/formateMusic";
- import { getMusicSheetDetail, getInstrumentCode } from "./utils/baseApi"
- import { getQuery } from "/src/utils/queryString";
- import { followData, skipNotePractice } from "/src/view/follow-practice/index"
- import { changeSongSourceByBeat } from "/src/view/audio-list"
- import { moveSmoothAnimation, smoothAnimationState, moveSmoothAnimationByPlayTime, moveTranslateXNum, destroySmoothAnimation, calcClientWidth } from "/src/page-instrument/view-detail/smoothAnimation"
- import { storeData } from "/src/store";
- import { downloadXmlStr } from "./view/music-score"
- import { musicScoreRef, headerColumnHide } from "/src/page-instrument/view-detail/index"
- import { headTopData } from "/src/page-instrument/header-top/index";
- import { api_lessonTrainingTrainingStudentDetail } from "/src/page-instrument/api"
- import { undoData, moveData } from "/src/view/plugins/move-music-score"
- import { speedBeatTo, unitImgs } from "/src/helpers/beatConfig"
- import { musicalInstrumentCodeInfo, instruments, fixInstrumentNameCode } from "/src/constant/instruments";
- const query: any = getQuery();
- export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
- export enum EnumMusicRenderType {
-
- staff = "staff",
-
- firstTone = "firstTone",
-
- fixedTone = "fixedTone",
- }
- export const musicscoresettingKey = "musicscoresetting";
- export type IPlayState = "music" | "background" | "mingSong";
- export type IAudioState = "play" | "paused";
- export enum IPlatform {
- APP = "APP",
- PC = "PC",
- }
- export type ISonges = {
- background?: string
- music?: string
- }
- 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];
- const state = reactive({
-
- platform: "" as IPlatform,
- appName: "" as "GYM" | "COLEXIU",
- musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
-
- musicRendered: false,
-
- detailId: "",
-
- xmlUrl: "",
-
- subjectId: 0 as number,
- trackId: 0 as string | number,
- isVip: false,
-
- categoriesId: 0,
-
- categoriesName: "",
-
- enableEvaluation: true,
-
- enableNotation: false,
-
- specialShowNotation: false,
-
- examSongId: "",
-
- cbsExamSongId: "",
-
- examSongName: "",
-
- coverImg: "",
-
- extConfigJson: {} as any,
-
- extStyleConfigJson: {} as any,
-
- extJianStyleConfigJson: {} as any,
-
- isOpenMetronome: false,
-
- isSingOpenMetronome: false,
-
- isShowFingering: false,
-
- music: "",
-
- accompany: "",
-
- fanSong: "",
-
- banSong: "",
-
- mingSong: "",
-
- mingSongGirl:"",
-
- beatSong: {
- music: "",
- accompany: "",
- fanSong: "",
- banSong: "",
- mingSong: "",
- mingSongGirl: ""
- },
-
- midiUrl: "",
-
- parentCategoriesId: 0,
-
- musicSheetCategoriesId: 0,
-
- bizMusicCategoryId: 0,
-
- playMode: "MP3" as "MP3" | "MIDI",
-
- speedBeatUnit: "1/4",
-
- speed: 0,
-
- originSpeed: 0,
-
- playIngSpeed: 0,
-
- track: "",
-
- partIndex: 0,
-
- combinePartIndexs:[],
-
- needTick: false,
-
- needSingTick: false,
-
- isMixBeat: true,
-
- osmd: null as unknown as OpenSheetMusicDisplay,
-
- isSpecialBookCategory: false,
-
- playState: "paused" as IAudioState,
-
- playEnd: false,
-
- playType: "play" as "play" | "sing",
-
- playSource: "music" as IPlayState,
-
- playProgress: 0,
-
- activeNoteIndex: 0,
-
- activeMeasureIndex: -1,
-
- sectionStatus: false,
-
- section: [] as any[],
-
- sectionBoundingBoxs: [] as any[],
-
- isOpenPrepare: false,
-
- sectionFirst: null as any,
-
- times: [] as any[],
-
- modeType: "practise" as "practise" | "follow" | "evaluating",
-
- setting: {
-
- soundEffect: true,
-
- eyeProtection: false,
-
- camera: false,
-
- cameraOpacity: 70,
-
- repeatAutoPlay: true,
-
- displayFingering: true,
-
- displayCursor: true,
-
- frequency: 0,
-
- evaluationDifficulty: "BEGINNER" as IDifficulty,
-
- saveToAlbum: true,
-
- enableAccompaniment: true,
-
- reactionTimeMs: 0,
-
- beatVolume: 50,
-
- combineMultipleRest: true,
- },
-
- baseFrequency: 440,
-
- fixtime: 0,
-
- evXmlBeginTime: 0,
-
- secondEvXmlBeginTime: 0,
-
- evXmlBeginArr: [] as any,
-
- xmlHasTimes: false,
-
- xmlHasTimeGap: false,
-
- timegapRepeatMeasureIndex: 1,
-
- fingeringInfo: {} as IFingering,
-
- scrollContainer: "musicAndSelection",
-
- isPercussion: false,
-
- evaluationStandard: '',
-
- repeatedBeats: 0,
-
- partListNames: [] as any,
-
- gradual: [] as GradualNote[],
-
- gradualVersion: GradualVersion.BASE as GradualVersion,
-
- gradualTimes: null as GradualTimes,
-
- multitrack: 0,
-
- zoom: 0.8,
-
- musicZoom: 1,
-
- isSelectMeasureMode: false,
-
- isReport: false,
-
- isHideEvaluatReportSaveBtn: false,
-
- isConcert: false,
-
- userChooseEndIndex: 0,
-
- repeatInfo: [] as any,
-
- canSelectTracks: [] as any,
-
- subjectCodeId: 0 as number,
-
- musicalCodeId: 0 as number,
-
- musicalCode: '' as any,
-
- isCombineRender: false,
-
- isScoreRender: false,
-
- defaultScoreRender: false,
-
- noMusicSource: false,
-
- measureTime: 0,
-
- beatStartTime: 0,
-
- isPreView: false,
-
- isCbsView: false,
-
- isEvaluatReport: false,
-
- midiPlayIniting: false,
-
- songs: {} as ISonges,
- isAppPlay: false,
-
- audiosInstance: null as any,
-
- durationNum: 0,
- midiSectionStart: 0,
-
- audioDone: false,
-
- isSingleLine: false,
-
- isEvxml: false,
- noTimes: [] as any,
-
- playBtnDirection: "left" as "left" | "right",
-
- musicScoreBtnDirection: "right" as "left" | "right",
-
- isAttendClass: false,
-
- guideInfo: null as any,
- noteCoords: [] as any,
- specialPosInit: false,
-
- paymentType: null,
-
- defaultModeType: 1,
-
- maxLyricNum: 0,
-
- vfmeasures: [] as SVGAElement[],
-
- musicComposer: '',
-
- musicLyricist: '',
-
- isLoading: true,
-
- loadingText: '音频资源加载中,请稍后…',
-
- isSimplePage: false,
-
- originAudioPlayRate: 1,
-
- basePlayRate: 1,
-
- hasDriverPop: false,
-
- noSavePopShow: true,
-
- xmlHasLyric: false,
-
- isCreateImg: false,
-
- workSectionNeedReset: false,
-
- melodyLine: true,
-
- isCTone: false,
- evxmlAddPartName: false,
-
- instrumentId: null,
-
- isWorkDone: false,
-
- firstMeasureNumber: 1,
- totalMeasureNumber: 0,
- isFullEvaluatWork: false,
-
- isAutoRePlay: false,
-
- speedIcon: 'speed3',
- isSingleMutliTrack: false,
- showWorkDonePop: false,
-
- headTopHeight: 0,
- });
- const browserInfo = browser();
- let offset_duration = 0;
- export const customData = reactive({
-
- customNoteRealValue: [] as any,
-
- customNoteCurrentTime: false,
- });
- export const setStep = () => {
-
- if (state.playState !== "play") {
- console.log("暂停播放");
- return;
- }
- let startTime = Date.now();
- requestAnimationFrame(() => {
- const endTime = Date.now();
-
- if (endTime - startTime < 16.7) {
- handlePlaying();
- setStep();
- } else {
- setTimeout(() => {
- handlePlaying();
- setStep();
- }, 16.7);
- }
- });
- };
- export const onPlay = () => {
- console.log("开始播放", '音频总时长:', getAudioDuration());
- state.playEnd = false;
-
- offset_duration = 0.2;
- setStep();
- };
- const autoResetPlay = () => {
-
- if (state.modeType !== "practise" || state.showWorkDonePop) return;
- skipNotePlay(0, true);
-
- if (!state.setting.repeatAutoPlay) return;
- offsetTop = 0;
- scrollViewNote();
- setTimeout(() => {
- if (state.showWorkDonePop) return
-
- state.isAutoRePlay = true;
- togglePlay("play");
- }, 1000);
- };
- export const onEnded = () => {
- console.log("音频播放结束");
-
-
-
-
- if (state.playEnd) {
- console.log('音频播放结束,无需再次执行')
- return
- }
-
- state.playEnd = true;
- state.playState = "paused";
-
- audioListStart(state.playState);
-
- handleEndEvaluat(true);
-
- autoResetPlay();
- };
- const dynamicShowPlaySpeed = (index: number) => {
-
- const item: any = state.times[index];
- if (item && item.measureSpeed ) {
-
- const newSpeed = state.basePlayRate * item.measureSpeed
- if (state.speed !== newSpeed) {
- state.speed = newSpeed;
- }
- }
-
- }
- export const initSetPlayRate = () => {
-
- if (state.isAutoRePlay) {
- state.isAutoRePlay = false
- return
- }
-
- let item: any = state.times[state.activeNoteIndex];
- console.log('播放状态',state.playState)
- if (item && item.measureSpeed) {
- const ratio = state.speed / item.measureSpeed
-
- state.basePlayRate = ratio || 1;
- console.log('播放倍率',state.basePlayRate)
- }
- }
- export const resetBaseRate = (idx?: number) => {
- const index = idx ? idx : 0;
- const currentItem: any = state.times[index];
- const currentSpeed = currentItem?.measureSpeed ? currentItem.measureSpeed : state.originSpeed;
- console.log('速度2',currentSpeed)
- state.speed = currentSpeed
-
- state.basePlayRate = 1;
- }
- const handlePlaying = () => {
- const currentTime = getAudioCurrentTime();
- const duration = getAudioDuration();
- state.playProgress = (currentTime / duration) * 100;
- let item = getNote(currentTime);
- if (item) {
-
- if (state.sectionStatus && state.section.length === 2) {
-
- const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
- const selectEndItem = state.section[1];
-
- if (state.repeatInfo.length) {
- const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
- const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
- if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
- const preItem = state.times[item.i - 1]
- if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
- const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
-
- if (skipItem) {
-
- setAudioCurrentTime(skipItem.time, skipItem.i);
- gotoNext(skipItem);
- return
- }
- }
- }
- }
-
-
-
- if (currentTime - selectEndItem.endtime >= 0) {
- console.log("选段播放结束", state.setting.repeatAutoPlay);
-
- if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
- onEnded();
- return;
- }
-
- if (state.modeType === "practise" && state.sectionStatus) {
- onEnded();
-
-
- resetPlaybackToStart();
- return;
- }
- item = selectStartItem;
- setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
- }
- }
- gotoNext(item);
- dynamicShowPlaySpeed(item.i);
- }
-
-
-
-
-
-
-
- if (state.isSingleLine) {
- moveSmoothAnimationByPlayTime()
- }
- };
- export const skipNotePlay = async (itemIndex: number, isStart = false) => {
- if (state.isPreView) return;
- console.log('点击音符')
-
- state.isSingleLine && (smoothAnimationState.oldCurrentTime = 0)
- const item = state.times[itemIndex];
- let itemTime = item.time;
- if (isStart) {
- itemTime = 0;
- }
- if (item) {
-
- if (item.measureSpeed && state.section.length < 2) {
- state.speed = state.basePlayRate * 10000 * item.measureSpeed / 10000
- }
- setAudioCurrentTime(itemTime, itemIndex);
-
- gotoNext(item, true);
-
-
- if (state.isAppPlay) {
- await api_cloudSetCurrentTime({
- currentTime: itemTime * 1000,
- songID: state.examSongId,
- })
- audioData.progress = itemTime
- state.midiSectionStart = itemTime
- }
-
- if (followData.start) {
- skipNotePractice()
- }
- }
- };
- export const togglePlay = async (playState: "play" | "paused", isForceCLoseToast?:boolean) => {
-
- if (!state.isAppPlay && !state.audioDone) {
- if (!isForceCLoseToast) showToast('音频资源加载中,请稍后')
- return
- }
-
- if (playState === 'play' && state.modeType === "practise" && state.playMode !== "MIDI") {
- console.log("设置音源")
- changeSongSourceByBeat(metronomeData.disable)
- }
- if (playState === 'play') {
- offsetTop = 0;
- scrollViewNote();
- }
-
- if (state.isAppPlay) {
- if (playState === "paused") {
- await api_cloudSuspend({
- songID: state.examSongId,
- })
- state.playState = 'paused'
-
- closeTick()
- return
- }
- skipNotePlay(state.activeNoteIndex, false);
- await api_cloudChangeSpeed({
- speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
- originalSpeed: state.originSpeed,
- songID: state.examSongId,
- });
- const cloudGetMediaStatus = await api_cloudGetMediaStatus();
- const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
- state.playState = status
- } else {
- state.playState = playState;
- }
- if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
- resetPlaybackToStart();
- }
-
- if (state.playState === "paused") {
- closeTick()
- }
-
- const isOneMeasureNumberXML = state.section.length === 2 && state.section[0].MeasureNumberXML === 2
- if (state.playState === "play" && getAudioCurrentTime() === 0 && !isOneMeasureNumberXML && ((state.playType === "play" && state.needTick) || (state.playType === "sing" && state.needSingTick))) {
-
- if ((state.playType === "play" && !state.isOpenMetronome) || (state.playType === "sing" && !state.isSingOpenMetronome)) {
- const tickend = await handleStartTick();
-
-
- if (!tickend) {
- state.playState = "paused";
- return false;
- }
- } else {
- handleStartTick()
- }
- }
-
- if (state.playState == "play") {
- if (state.sectionStatus && state.section.length < 2) {
- clearSelection();
- }
- }
- initSetPlayRate();
- audioListStart(state.playState);
- return true;
- };
- export const handleStopPlay = () => {
- state.playState = "paused";
- audioListStart(state.playState);
- };
- export const resetPlaybackToStart = () => {
-
- if (state.sectionStatus && state.section.length === 2) {
- state.section = formateSelectMearure(state.section);
- return;
- } else {
-
- metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
- }
- skipNotePlay(0, true);
- };
- export const gotoCustomNote = (index: number) => {
- try {
- state.osmd.cursor.reset();
- } catch (error) { }
- for (let i = 0; i < index; i++) {
- state.osmd.cursor.next();
- }
- };
- const computedDistance = (x: number, y: number) => {
- let minDistance = -1, minidx = 0;
- let a, b, c;
- state.noteCoords.forEach((note: any, idx: any) => {
-
- a = Math.abs(note.x - x)
- b = Math.abs(note.y - y)
-
- c = Math.sqrt(a * a + b * b) as 0
- c = Number(c.toFixed(0)) as 0
- if (c !== 0 && (minDistance === - 1 || c < minDistance)) {
-
- minDistance = c
- minidx = idx
- }
- })
- return minidx
- };
- const customNotePosition = (note: any, cursor: any) => {
- const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
- if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
- const pageLeft = document.getElementById('scrollContainer')?.getBoundingClientRect()?.x || 0;
-
- const element = document.getElementById('cursorImg-0')?.getBoundingClientRect?.() || { x: 0, y: 0 };
-
- if (element.x && element.y) {
- const noteIdx = computedDistance(element.x, element.y);
- const targetX = state.noteCoords[noteIdx]?.x - pageLeft;
- console.log('音符索引', noteIdx)
- cursor.cursorElement.style.left = targetX + "px";
- cursor.cursorElement.style.transform = `translateX(0px)`;
- }
- }
- }
- const setCursorPosition = (note: any, cursor: any, flag?: string) => {
-
- if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
-
- if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
- return
- }
- const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
- if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
-
- const cursorLeft = cursor?.cursorElement?.style?.left ? parseFloat(cursor.cursorElement.style.left) : 0;
- let patchX = 0;
- if (state.cbsExamSongId == '1788502467554750466') {
- if (state.musicRenderType === EnumMusicRenderType.firstTone) {
- 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;
- }
- if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
- 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;
- }
- } else if (state.cbsExamSongId == '1788501975122489346') {
- if (state.musicRenderType === EnumMusicRenderType.firstTone) {
- 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;
- }
- if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
- 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;
- }
- }
- if (flag === 'refresh' || (flag === 'init' && !state.specialPosInit)) {
-
- cursor.cursorElement.style.left = cursorLeft + patchX + "px";
- state.specialPosInit = true;
- }
- } else {
- nextTick(() => {
- let bbox = note.bbox;
- if (!bbox) {
- const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
- x: 0,
- y: 0,
- };
- const parentLeft = musicContainer.x || 0;
- const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
- if (noteEle) {
- const noteHead = noteEle.querySelector(".vf-numbered-note-head");
- const noteHeadBbox = noteHead?.getBoundingClientRect?.();
- if (noteHeadBbox) {
- note.bbox = {
- left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
- width: noteHeadBbox.width * 1.5,
- };
- bbox = note.bbox;
- }
- }
- }
- if (!bbox) return;
- const baseW = state.platform === IPlatform.PC ? 29 : 18;
- const width = (bbox.width - baseW) / 3;
-
- cursor.cursorElement.style.left = bbox.left + "px";
- cursor.cursorElement.style.transform = `translateX(${width}px)`;
- });
- }
- }
- };
- export const gotoNext = (note: any, skipNote?: boolean) => {
-
- const num = note.i;
- if (state.activeNoteIndex === note.i) {
-
-
-
-
-
-
-
- if(state.playState === "paused"){
- fillWordColor();
- }
- if (state.isSingleLine && state.playState === "paused") {
- moveSvgDom(skipNote);
- }
- return;
- }
- const osmd = state.osmd;
- let prev = state.activeNoteIndex;
- state.activeNoteIndex = num;
- state.activeMeasureIndex = note.MeasureNumberXML;
- dynamicShowPlaySpeed(state.activeNoteIndex);
- if (prev && num - prev === 1) {
-
-
-
-
-
- osmd.cursor.next();
- } else if (prev && num - prev > 0) {
- while (num - prev > 0) {
- prev++;
-
- osmd.cursor.next();
- }
- } else {
- gotoCustomNote(num);
- }
-
-
-
-
-
-
- fillWordColor();
-
- if (state.isSingleLine && state.playState === "paused") {
- moveSvgDom(skipNote);
- }
- scrollViewNote();
- };
- export const getNote = (currentTime: number) => {
- const times = state.times;
- const len = state.times.length;
-
- if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay && !state.isSimplePage) {
-
- return;
- }
- let _item = null as any;
- for (let i = state.activeNoteIndex; i < len; i++) {
- let item = times[i];
- const prevItem = times[i - 1];
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if (currentTime >= item.time) {
- if (!prevItem || item.time != prevItem.time) {
- _item = item;
- }
- } else {
- break;
- }
- }
-
- return _item;
- };
- export const handleResetPlay = () => {
-
- if (state.isAppPlay) {
- audioData.progress = 0
- }
-
-
-
-
-
- resetPlaybackToStart();
-
- togglePlay("play");
- };
- export const handleSetSpeed = (speed: number) => {
-
- state.speed = speed;
-
-
- const currentItem: any = state.times[state.activeNoteIndex];
- state.basePlayRate = currentItem?.measureSpeed ? state.speed / currentItem.measureSpeed : state.speed / state.originSpeed;
- const actualRate = state.originAudioPlayRate * state.basePlayRate;
- console.log('速度设置',speed,'小节计算的倍率',state.basePlayRate,'实际播放倍率',actualRate)
- };
- export const clearSelection = () => {
- state.sectionStatus = false;
- state.section = [];
- closeToast();
- };
- export const handleChangeSection = () => {
-
- if (state.sectionStatus) {
- togglePlay("paused");
- clearSelection();
-
- resetBaseRate(state.activeNoteIndex);
-
- state.sectionFirst = null;
- return;
- }
- state.sectionStatus = true;
-
- if (state.sectionStatus) {
- togglePlay("paused");
- }
- showToast({
- message: "请选择开始小节",
- duration: 0,
- position: "top",
- className: "selectionToast",
- });
- };
- const formateSelectMearure = (_list: any[]): any[] => {
- if (!_list.length) return [];
- const list = _list.sort((a, b) => a.time - b.time);
- const startXml = list[0]?.measureOpenIndex;
- const endXml = list.last()?.measureOpenIndex;
- const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
- const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
-
- if (!selectStartMeasure.length || !selectEndMeasure.length) {
- clearSelection();
- return [];
- }
- list[0] = selectStartMeasure[0];
- list[1] = selectEndMeasure.last();
- let startItemINdex = list[0].i;
-
- if (state.isOpenPrepare) {
- const startXmlIndex = list[0].MeasureNumberXML;
- state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
- startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
- }
- skipNotePlay(startItemINdex, startItemINdex === 0);
- return list;
- };
- export const handleSelection = (item: any) => {
- if (!state.sectionStatus || state.section.length > 1) return;
- if (state.section.length !== 2 && item) {
- state.section.push(item);
- if (state.section.length === 2) {
- setSection(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
-
- closeToast();
- }
- }
- if (state.section.length === 1) {
- showToast({
- message: "请选择结束小节",
- duration: 0,
- position: "top",
- className: "selectionToast",
- });
- }
- };
- export const setSection = (start: number, end: number, userSpeed?: number) => {
- const startNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
- )
- const endNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
- )
- state.userChooseEndIndex = end
- const lastEndId = endNotes[endNotes.length - 1].noteId
- let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
-
- const canRepeatInfo = verifyCanRepeat(start, end)
- console.log('能否重播', canRepeatInfo)
- const isCanRepeat = canRepeatInfo.canRepeat
-
-
- let isSkipVolta = false;
- if (lastEndNotes.length === 1) {
- isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
- }
- let currentEndNum: number = end
- const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
- while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
- currentEndNum = currentEndNum - 1
- const newEndNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
- )
- const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
- lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
- }
- const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
- const startNote = startNotes[0]
-
- const endNote = lastEndNotes[endIdx]
- if (startNote && endNote) {
- state.isSelectMeasureMode = true;
-
- hanldeDirectSelection([startNote, endNote]);
-
- if (userSpeed) {
- handleSetSpeed(userSpeed);
- }
- }
- }
- export const hanldeDirectSelection = (list: any[]) => {
- if (!Array.isArray(list) || list.length !== 2) return;
- state.sectionStatus = true;
- setTimeout(() => {
- state.section = formateSelectMearure(list);
-
- const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
- if (currentItem.measureSpeed && query.workRecord === undefined) {
- handleSetSpeed(currentItem.measureSpeed);
- }
- console.log('选段小节', state.section)
- }, 0);
- };
- let offsetTop = 0, musicScrollTop = 0;
- export const scrollViewNote = (resetTop?: boolean) => {
-
- const noteId = state.times[state.activeNoteIndex].id;
- if (state.isSingleLine) {
- return;
- }
- if (state.activeNoteIndex <= 1 || resetTop) {
- offsetTop = 0;
- }
- const domId = "vf" + noteId;
-
- const cursorElement: any = !noteId && state.times[state.activeNoteIndex]?.totalMultipleRestMeasures ? document.querySelector(`.measureIndex_${state.activeMeasureIndex}`) : document.querySelector(`[data-vf=${domId}]`)?.parentElement;
- const musicAndSelection = document.getElementById(state.scrollContainer)!;
- if (!state.headTopHeight) {
- state.headTopHeight = document.querySelector('.headHeight')?.getBoundingClientRect()?.height || 100;
- }
- if (!cursorElement || !musicAndSelection) {
- return
- }
-
- const noteCenterOffsetTop = cursorElement ? cursorElement?.offsetTop + (cursorElement?.offsetHeight/2) : 0;
-
- if (Math.abs(musicAndSelection?.scrollTop - musicScrollTop) > 30) {
-
- } else {
- if (offsetTop === cursorElement.offsetTop || Math.abs(offsetTop - cursorElement.offsetTop) < 30) return;
- }
-
- offsetTop = cursorElement.offsetTop;
- if (offsetTop > (state.headTopHeight + 30)) {
- musicScrollTop = (offsetTop - state.headTopHeight - 30) * state.musicZoom
- musicAndSelection.scrollTo({
- top: (offsetTop - state.headTopHeight - 30) * state.musicZoom,
- behavior: "smooth",
- });
- } else {
- musicScrollTop = 0
- musicAndSelection.scrollTo({
- top: 0,
- behavior: "smooth",
- });
- }
- };
- export const isRhythmicExercises = () => {
- return state.examSongName.indexOf("节奏练习") > -1;
- };
- export const handleRessetState = () => {
-
- state.noSavePopShow = true;
- clearSelection();
- skipNotePlay(0, true);
- resetBaseRate();
-
- if (state.isAppPlay) {
- audioData.progress = 0;
- }
- if (state.modeType === "evaluating") {
- handleStartEvaluat();
- } else if (state.modeType === "practise") {
- togglePlay("paused", true);
- } else if (state.modeType === "follow") {
- toggleFollow(false);
- }
- };
- export default state;
- export const evaluatCreateMusicPlayer = () => {
- return api_createMusicPlayer({
- musicSrc: state.accompany || state.music,
-
- tuneSrc: "https://oss.dayaedu.com/MECMP/1722593665681.mp3",
- checkFrequence: 496,
- });
- };
- export const getMusicDetail = async (id: string, type?: string) => {
- const res = await getMusicSheetDetail(id, type);
- if (res?.code === 200) {
- await getMusicInfo(res)
- }
- };
- const initInstrumentCode = async () => {
- const res = await getInstrumentCode();
- if (res?.code === 200 && res.data?.length) {
- for (let item of res.data) {
- const codes = item.code.split(',') || [item.code]
- codes.forEach((code: any) => {
- instruments[code] = item.name
- })
- }
- }
-
- }
- const getMusicInfo = async (res: any) => {
- try {
- await initInstrumentCode()
- } catch (error) {
-
- }
-
- state.isScoreRender = res.data?.isScoreRender
-
- state.defaultScoreRender = res.data?.defaultScoreRender
-
- let xmlString = await fetch(res.data.xmlFileUrl).then((response) => response.text());
- xmlString = xmlAddPartName(xmlString);
- downloadXmlStr.value = xmlString
- const tracks = xmlToTracks(xmlString)
-
- state.isMixBeat = res.data?.isMixBeat
-
- let partIndexs = query["part-index"] ? query["part-index"].split(",") : ["-1"]
-
- if (query["part-name"]) {
- const partValue = decodeURIComponent(query["part-name"]) || ''
- let nameIdx = tracks.findIndex((item: any) => item == partValue)
- partIndexs = [nameIdx]
- }
- partIndexs = partIndexs.map((indexStr:string) => {
- return parseInt(indexStr)
- }).sort((a, b) => a - b);
- let partIndex = partIndexs[0]
-
- if(partIndexs.length > 1){
- partIndex = 999
- state.combinePartIndexs = partIndexs
- }
-
- if (state.isEvaluatReport) {
- partIndex = state.partIndex;
- }
-
- const workRecord = query.workRecord
- let workRecordInstrumentId:undefined | string
- if(workRecord){
- const res = await api_lessonTrainingTrainingStudentDetail(workRecord);
- if (res?.code === 200) {
- workRecordInstrumentId = res.data?.instrumentId
- }
- }
-
- state.canSelectTracks = res.data.multiTracksSelection === "null" || res.data.multiTracksSelection === "" || res.data.multiTracksSelection === null ? [] : res.data.multiTracksSelection?.split(',');
- state.canSelectTracks = state.canSelectTracks.map((item: any)=>item.trim())
-
- if (state.combinePartIndexs.length) {
- (window as any).DYFirstTrackName = tracks[state.combinePartIndexs[0]] || '';
- } else {
- (window as any).DYFirstTrackName = '';
- }
-
- const { track, index, musicalInstrumentId } = state.isSimplePage ? { track:tracks[0], index: state.partIndex, musicalInstrumentId: '' } : initMusicSource(res.data, tracks, partIndex, workRecordInstrumentId)
-
- const realTrack = musicalInstrumentId && res.data?.musicalInstruments?.length ? res.data?.musicalInstruments.find((item: any) => item?.id == musicalInstrumentId)?.code?.split(',')?.[0] : '';
- const musicInfo = {
- ...res.data,
- track: res.data.musicSheetType === 'CONCERT' ? track : realTrack
- };
- console.log("🚀 ~ musicInfo:", musicInfo);
- setState(musicInfo, index);
- };
- function xmlToTracks(xmlString: string) {
- const xmlParse = new DOMParser().parseFromString(xmlString, "text/xml");
- const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
- return partNames.reduce((arr: string[], item) => {
- const textContent = item?.textContent?.trim()
- if (textContent?.toLocaleLowerCase() === "common") {
- (window as any).HasCommonTrack = true;
- }
- if (textContent?.trim()?.toLocaleLowerCase() !== "common" && textContent) {
- arr.push(textContent)
- }
- return arr
- }, []);
- }
- function initMusicSource(data: any, tracks: string[], partIndex: number, workRecordInstrumentId?: string) {
- let track:string,index:number, musicalInstrumentId: string
- const instrumentId = workRecordInstrumentId || query.instrumentId || storeData.user?.instrumentId
- state.instrumentId = instrumentId;
- let { musicSheetType, isAllSubject, musicSheetSoundList, musicSheetAccompanimentList } = data
- musicSheetSoundList || (musicSheetSoundList = [])
- musicSheetAccompanimentList || (musicSheetAccompanimentList = [])
- let musicObj, accompanyObj, fanSongObj, banSongObj
-
- if (musicSheetType === "SINGLE") {
- accompanyObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "PLAY"
- })
-
- musicObj = musicSheetSoundList.find((item: any) => {
- return isAllSubject ? item.audioPlayType === "PLAY" : (item.audioPlayType === "PLAY" && item.musicalInstrumentId == instrumentId)
- })
-
- if(!musicObj && !instrumentId){
- musicObj = musicSheetSoundList.find((item: any) => {
- return item.audioPlayType === "PLAY"
- })
- }
- fanSongObj = musicSheetSoundList.find((item: any) => {
- return item.audioPlayType === "SING"
- })
- banSongObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "SING"
- })
- track = musicObj?.track
- index = tracks.findIndex(item => {
- return item === track
- })
- musicalInstrumentId = musicObj?.musicalInstrumentId
- } else {
-
-
- if(state.isScoreRender && (partIndex===999 || (state.defaultScoreRender && partIndex===-1)) || state.combinePartIndexs.length > 1){
-
- state.isCombineRender = true
- banSongObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "SING"
- })
-
-
- if(banSongObj){
- fanSongObj = {
- audioFileUrl: banSongObj.scoreAudioFileUrl,
- audioBeatMixUrl: banSongObj.scoreAudioBeatMixUrl
- }
- }
-
- if(state.combinePartIndexs.length) {
-
- state.combinePartIndexs.map( partI => {
- const musicSheetSound = musicSheetSoundList.find((item:any)=>{
- return item.track?.toLowerCase().trim() === tracks[partI]?.toLowerCase().trim() && item.audioPlayType === "PLAY"
- })
- musicSheetSound?.audioFileUrl && (audioData.combineMusics[partI] = musicSheetSound.audioFileUrl)
- })
- }else{
- tracks.map((itemTrack:any, partI:number) => {
- const musicSheetSound = musicSheetSoundList.find((item:any)=>{
- return item.track?.toLowerCase().trim() === itemTrack?.toLowerCase().trim() && item.audioPlayType === "PLAY"
- })
- musicSheetSound?.audioFileUrl && (audioData.combineMusics[partI] = musicSheetSound.audioFileUrl)
- })
- }
-
- accompanyObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "PLAY"
- })
- track = "总谱"
- index = 999
- musicalInstrumentId = ''
- }else{
-
- track = partIndex === -1 ? tracks.find(value => state.canSelectTracks.includes(value))! : tracks[partIndex]
-
- musicObj = musicSheetSoundList.find((item: any) => {
- return item.audioPlayType === "PLAY" && item.track === track
- })
- fanSongObj = musicSheetSoundList.find((item: any) => {
- return item.audioPlayType === "SING" && item.track === track
- })
- banSongObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "SING"
- })
- accompanyObj = musicSheetAccompanimentList.find((item: any) => {
- return item.audioPlayType === "PLAY"
- })
- index = tracks.findIndex(item => {
- return item === track
- })
- musicalInstrumentId = musicObj?.musicalInstrumentId
- }
- state.partListNames = tracks
- }
-
- if (!musicObj?.audioFileUrl && !accompanyObj?.audioFileUrl && !fanSongObj?.audioFileUrl && !banSongObj?.audioFileUrl && !fanSongObj?.solmizationFileUrl && !fanSongObj?.femaleSolmizationFileUrl) {
- state.noMusicSource = true
-
- if(musicSheetType === "SINGLE"){
-
- if(data.playMode === "MIDI" && !data.midiFileUrl) {
-
- if(!query.isPreView){
- throw new Error("该曲目无任何音源");
- }
- }
- }
- }
- Object.assign(state, {
- music: musicObj?.audioFileUrl,
- accompany: accompanyObj?.audioFileUrl,
- fanSong: fanSongObj?.audioFileUrl,
- banSong: banSongObj?.audioFileUrl,
- })
-
- if(!fanSongObj?.solmizationFileUrl){
- state.mingSong = fanSongObj?.femaleSolmizationFileUrl
- }else{
- state.mingSong = fanSongObj?.solmizationFileUrl
- state.mingSongGirl = fanSongObj?.femaleSolmizationFileUrl
- }
-
- if(state.isMixBeat) {
- Object.assign(state.beatSong, {
- music: musicObj?.audioBeatMixUrl,
- accompany: accompanyObj?.audioBeatMixUrl,
- fanSong: fanSongObj?.audioBeatMixUrl,
- banSong: banSongObj?.audioBeatMixUrl
- })
-
- if(!fanSongObj?.solmizationBeatUrl){
- state.beatSong.mingSong = fanSongObj?.femaleSolmizationBeatUrl
- }else{
- state.beatSong.mingSong = fanSongObj?.solmizationBeatUrl
- state.beatSong.mingSongGirl = fanSongObj?.femaleSolmizationBeatUrl
- }
- }
- return {
- index,
- track,
- musicalInstrumentId
- }
- }
- const setState = (data: any, index: number) => {
-
- const localStoragePlayType = localStorage.getItem("musicScorePlayType")
- if(localStoragePlayType) {
- localStorage.removeItem("musicScorePlayType")
- const fields = localStoragePlayType.split(',')
- state.playType = fields[0] as any
- state.playSource = fields[1] as any
- }
-
- const playObj = {
- "play_music":"music",
- "play_background":"accompany",
- "play_mingSong":"mingSong",
- "sing_music":"fanSong",
- "sing_background":"banSong",
- "sing_mingSong":"mingSong",
- } as any
-
-
- if(!state[playObj[`${state.playType}_${state.playSource}`]]){
- if(state.playType === "play"){
- if(state.music){
- state.playSource = "music"
- }else if(state.accompany){
- state.playSource = "background"
- }else{
- if(state.fanSong){
- state.playType = "sing"
- state.playSource = "music"
- }else if(state.banSong){
- state.playType = "sing"
- state.playSource = "background"
- }else if(state.mingSong){
- state.playType = "sing"
- state.playSource = "mingSong"
- }
- }
- }else{
- if(state.fanSong){
- state.playSource = "music"
- }else if(state.banSong){
- state.playSource = "background"
- }else if(state.mingSong){
- state.playSource = "mingSong"
- }else{
- if(state.music){
- state.playType = "play"
- state.playSource = "music"
- }else if(state.accompany){
- state.playType = "play"
- state.playSource = "background"
- }
- }
- }
- }
- state.appName = "COLEXIU";
- state.detailId = data.bizId;
- state.xmlUrl = data.xmlFileUrl;
- state.paymentType = data.paymentType
- state.partIndex = index >= 0 ? index : 0;
- state.trackId = data.track;
- state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
-
- const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
-
-
-
-
-
-
-
-
-
- state.categoriesId = data.musicCategoryId;
- state.categoriesName = data.musicTagNames;
-
- state.examSongId = data.bizId + "";
- state.cbsExamSongId = data.id + "";
-
- if (state.examSongId == '1795013331841662977') {
- ; (window as any).DYCustomHopscotch = [1,2,1,2,1,2,1,2]
- }
- ; (window as any).DYExamSongId = state.examSongId
- state.examSongName = data.name;
- state.coverImg = data.musicCover ?? "";
-
- if (state.isSimplePage) {
- state.isCombineRender = false;
- }
-
- const minCombineNum = data.musicSheetSoundList?.length ? Math.max(data.musicSheetSoundList?.length, 2) : 2;
- setCustom(state.isCombineRender ? minCombineNum : 0);
-
- if (data.extConfigJson) {
- try {
- state.extConfigJson = JSON.parse(data.extConfigJson as string);
- } catch (error) {
- console.error("解析扩展字段错误:", error);
- }
- }
- state.gradualTimes = state.extConfigJson.gradualTimes;
- state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
- state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
-
- state.needTick = !!data.isPlayBeat
- state.needSingTick = !!data.isPlaySingBeat
-
-
- state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
-
- state.isSingOpenMetronome = data.isPlaySingBeat && !data.isUseSingSystemBeat ? true : false
- state.isShowFingering = data.isShowFingering ? true : false;
-
- state.isAppPlay = data.playMode === 'MIDI';
- state.midiUrl = data.midiFileUrl;
- state.parentCategoriesId = data.musicTag;
- state.musicSheetCategoriesId = data.musicCategoryId;
- state.bizMusicCategoryId = data.bizMusicCategoryId
- state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
-
- state.speedBeatUnit = data.speedBeatUnit || "1/4"
-
- state.originSpeed = state.speed = speedBeatTo({unit: data.speedBeatUnit || "1/4",speed: parseFloat(data.playSpeed) || 0}, `1/4`);
-
-
- const track = data.code || data.track;
- state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
-
- if (state.isAppPlay) {
- state.enableEvaluation = state.midiUrl ? true : false
- } else {
- state.enableEvaluation = state.accompany || state.music ? true : false
- }
- state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
-
- state.isOpenPrepare = true;
- state.extStyleConfigJson = data.extStyleConfigJson || {}
- state.extJianStyleConfigJson = data.extJianStyleConfigJson || {}
-
-
-
-
- state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
- state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
-
- state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
-
-
-
-
-
-
- if (data.musicSheetType === "SINGLE" && data.playMode === 'MIDI' && data.musicalInstruments?.length) {
- const currentInstrumentId = query.instrumentId || storeData.user?.instrumentId;
- let midiTrackId = null
- if (currentInstrumentId) {
- midiTrackId = data.musicalInstruments.find((item: any) => item.id == currentInstrumentId)?.code?.split(',')?.[0]
- } else {
- midiTrackId = data.musicalInstruments[0]?.code?.split(',')?.[0]
- }
- state.trackId = midiTrackId || state.trackId
- }
- let code = matchVoicePart(state.trackId, "CONCERT")
- if (code == 1 || !code) {
- code = fixInstrumentNameCode(state.trackId)
- }
- state.fingeringInfo = subjectFingering(code);
- console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
- state.musicalCodeId = state.fingeringInfo?.id || 0
- state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
- ; (window as any).DYSubjectId = state.musicalCodeId
-
- ; (window as any).customSectionAmount = true
-
- ; (window as any).DYProjectName = 'musicScore';
-
- if (!state.fingeringInfo.name && state.setting.displayFingering) {
- state.setting.displayFingering = false
- }
-
- state.platform = query.platform?.toLocaleUpperCase() || "";
- if (state.platform === IPlatform.PC) {
-
- state.zoom = 1.5;
- if (query.zoom <= 1) {
- state.zoom = query.zoom ? Number(query.zoom) : state.zoom;
- } else {
- state.zoom = localStorage.getItem('scoreZoom') ? Number(localStorage.getItem('scoreZoom')) : state.zoom
- }
- state.enableEvaluation = false;
- }
- if (storeData.isApp) {
- state.zoom = localStorage.getItem('scoreZoom') ? Number(localStorage.getItem('scoreZoom')) : state.zoom
- }
-
-
-
-
-
-
-
-
- let musicalRenderType = ''
-
-
-
-
-
- musicalRenderType = data.scoreType === 'STAVE' ? 'staff' : data.scoreType === 'JIAN' ? 'fixedTone' : data.scoreType === 'FIRST' ? '' : 'firstTone';
- if (!state.isEvaluatReport) {
- state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
- }
- state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
-
- if (['1788501975122489346', '1788502467554750466', '1789839575249596417'].includes(state.cbsExamSongId)) {
- if (state.musicRenderType === 'fixedTone') {
- state.musicRenderType = EnumMusicRenderType.firstTone;
- }
- }
-
-
-
- state.enableNotation = data.isConvertibleScore
- state.specialShowNotation = !data.isConvertibleScore && data.scoreType !== 'STAVE';
- console.log("state对象", state);
-
- state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
- state.baseFrequency = Number(state.baseFrequency)
-
- if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
- state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
- } else {
- state.setting.frequency = state.setting.frequency || state.baseFrequency
- }
- state.playBtnDirection = query.imagePos === 'left' ? 'left' : 'right';
- state.isAttendClass = (query.imagePos === 'left' || query.imagePos === 'right') ? true : false;
- };
- const setCustom = (trackNum?: number) => {
- if (trackNum || state.extConfigJson.multitrack) {
- state.multitrack = trackNum || 0
- setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
- }
- };
- export const followBeatPaly = () => {
- let metroTimer: any = null;
- if (!followData.start) {
- clearTimeout(metroTimer)
- metroTimer = null
- return;
- }
- const time = state.measureTime * 1000 / metronomeData.totalNumerator / state.basePlayRate;
- requestAnimationFrame(() => {
- const endTime = Date.now();
- if (endTime - state.beatStartTime < time) {
- followBeatPaly();
- } else {
-
-
-
-
-
- metronomeData.metro?.simulatePlayAudio()
- state.beatStartTime = Date.now();
- followBeatPaly();
- }
- });
- };
- export const addNoteBBox = (list: any[]) => {
- const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
- x: 0,
- y: 0,
- };
- const parentLeft = musicContainer.x || 0;
- let voicesBBox: any = null;
- for (let i = 0; i < list.length; i++) {
- const note = list[i];
- const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
-
- let bbox: any = null;
- if (svgElement?.attrs.id) {
-
- bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
- const noteBbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBoundingClientRect?.() || { x: 0, width: 0 };
- bbox = {
- left: noteBbox.x - parentLeft - noteBbox.width / 4,
- x: bbox?.x * state.zoom,
- y: bbox?.y * state.zoom,
- width: bbox?.width * state.zoom,
- height: bbox?.height * state.zoom,
- }
- } else {
-
- let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
- const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
- if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
- currentVoicesBBox = voicesBBox;
- }
- let nextIndex = i + 1;
- while (!list[nextIndex]?.id && nextIndex < list.length) {
- nextIndex += 1;
- }
-
- let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
- if (list[nextIndex]?.id) {
-
- multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
- }
- const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
- bbox = currentVoicesBBox ? {
- bottom: currentVoicesBBox.bottom,
- height: 30,
- left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
- right: currentVoicesBBox.y,
- top: currentVoicesBBox.top,
- width: 1,
- x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
- y: currentVoicesBBox.y,
- svgBodyLeft: svgBodyBBox?.x,
- } : null;
- voicesBBox = currentVoicesBBox;
- }
- note.bbox = bbox;
- }
- }
- let prevActiveNoteIndex = -1
- export const fillWordColor = () => {
-
- if(prevActiveNoteIndex !== -1) {
- const prevActiveNoteId = state.times[prevActiveNoteIndex]?.svgElement?.attrs?.id
- const svgEl = document.getElementById(`vf-${prevActiveNoteId}`)
- const stemEl = document.getElementById(`vf-${prevActiveNoteId}-stem`)
- const stemLine = document.getElementById(`vf-${prevActiveNoteId}-lines`)
- svgEl?.classList.remove('noteActive')
- stemEl?.classList.remove('noteActive')
-
- svgEl?.parentElement?.classList.remove('voiceActive')
- const si = state.times[prevActiveNoteIndex].si || 0;
- svgEl?.parentElement?.querySelectorAll('rect')?.forEach((item: any) => {
- item?.classList.remove('rectActive');
- })
-
- }
- const activeNoteId = state.times[state.activeNoteIndex]?.svgElement?.attrs?.id
- const svgEl = document.getElementById(`vf-${activeNoteId}`)
- const stemEl = document.getElementById(`vf-${activeNoteId}-stem`)
- const stemLine = document.getElementById(`vf-${activeNoteId}-lines`)
- svgEl?.classList.add('noteActive')
- stemEl?.classList.add('noteActive')
-
-
- if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
-
-
- if (state.times[state.activeNoteIndex].noteElement?.length?.realValue >= 0.5) {
-
- if (state.times[state.activeNoteIndex].noteElement?.length?.realValue === 0.5) {
- const si = state.times[state.activeNoteIndex].si || 0;
- const halfNotes = state.times[state.activeNoteIndex].measures.filter((item: any) => item?.noteElement?.length?.realValue === 0.5) || [];
- const sIdx = halfNotes?.findIndex((item: any) => item?.noteElement === state.times[state.activeNoteIndex]?.noteElement);
- const filterRects = svgEl?.parentElement?.querySelectorAll('rect')?.length ? Array.from(svgEl?.parentElement?.querySelectorAll('rect')).filter(item => item.parentElement === svgEl?.parentElement) : [];
- filterRects?.[sIdx]?.classList.add('rectActive');
- } else {
- svgEl?.parentElement?.classList.add('voiceActive');
- }
- }
- }
- prevActiveNoteIndex = state.activeNoteIndex
-
- const currentNote = state.times[state.activeNoteIndex];
- const lyrics: SVGAElement[] = Array.from(document.querySelectorAll(".vf-lyric"));
- lyrics.forEach((lyric) => {
- lyric?.classList.remove('lyricActive')
- })
- const currentLyrics: SVGAElement[] = Array.from(document.querySelectorAll(`.lyric${currentNote?.noteId}`));
- currentLyrics.forEach((lyric, index) => {
- const lyricIndex = lyric.getAttribute('lyricIndex');
-
- const onlyOneLyric = currentNote.measures?.every((item: any) => item?.formatLyricsEntries?.length <= 1);
- if ((index === currentNote.repeatIdx && currentNote.repeatIdx + 1 == lyricIndex) || (currentNote.repeatIdx != index && !onlyOneLyric && currentNote.repeatIdx + 1 == lyricIndex) || (currentNote.repeatIdx > 0 && currentNote.formatLyricsEntries?.length === 1 && onlyOneLyric)) {
- lyric?.classList.add('lyricActive')
- }
-
- if ( currentNote.formatLyricsEntries.length == 2 && currentNote.repeatIdx >= 2 && index === (currentNote.repeatIdx - 2) ) {
- lyric?.classList.add('lyricActive')
- }
-
-
-
- })
- }
- export const moveSvgDom = (skipNote?: boolean) => {
-
- if (skipNote) {
-
- smoothAnimationState.translateXNum = 0
- moveTranslateXNum(0)
-
- moveSmoothAnimation(0, state.activeNoteIndex, false)
-
- const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x
- smoothAnimationState.osdmScrollDom!.scrollTo({
- left: distance,
- behavior: "smooth",
- });
- }
- }
- watch(
- () => state.playState,
- () => {
- if (state.isSingleLine) {
-
- if (!state.playEnd && state.playState === "paused") {
- moveTranslateXNum(0)
-
- requestAnimationFrame(() => {
- const scrollLeft = smoothAnimationState.osdmScrollDom!.scrollLeft
- smoothAnimationState.osdmScrollDom!.scrollLeft = scrollLeft + smoothAnimationState.translateXNum
- smoothAnimationState.translateXNum = 0
- });
- }
- }
- }
- )
- function getNeedReduceMultipleRestNum(currMeasureIndex: number) {
- let needReduceMultipleRestNum = 0;
- for (let noteIndex = 0; noteIndex < state.times.length; noteIndex++) {
- const note = state.times[noteIndex];
- if (note.MeasureNumberXML > currMeasureIndex) {
- break;
- }
- if (note.multipleRestMeasures && note.multipleRestMeasures > 1) {
- needReduceMultipleRestNum += 1;
- }
- }
- return needReduceMultipleRestNum
- }
- watch(
- () => state.activeMeasureIndex,
- () => {
-
- const currentNote = state.times[state.activeNoteIndex]
- state.speedIcon = unitImgs[currentNote.speedBeatUnit]
-
-
-
-
-
- state.vfmeasures.forEach((item: any, idx: number) => {
- const dataNum = item.getAttribute('data-num')
- let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
- let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
-
- if(!(nextDataNum && nextDataNum !== "undefined")){
- nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
- }
- const nextMeasureNum = Number(nextDataNum)
-
- if(measureNum === -1) {
- measureNum = nextMeasureNum
- }
- if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex))) {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(9,159,255,0.15)")
-
- if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML && state.section.length === 2){
- item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255,193,48,0.15)")
- }
- } else {
-
- if (state.section.length === 2) {
-
- let leftMeasureNumberXML = state.section[0].MeasureNumberXML
- let rightMeasureNumberXML = state.section[1].MeasureNumberXML
- if (leftMeasureNumberXML > rightMeasureNumberXML) {
- leftMeasureNumberXML = state.section[1].MeasureNumberXML
- rightMeasureNumberXML = state.section[0].MeasureNumberXML
- }
- if(measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML){
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", 'transparent')
- }
- if (measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML) {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(9,159,255,0.15)")
- }
-
- if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
- item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255,193,48,0.15)")
- }
- } else {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", 'transparent')
- }
- }
- })
- }
- );
- watch(
- () => state.section,
- () => {
- if (state.section.length === 2) {
-
- let leftMeasureNumberXML = state.section[0].MeasureNumberXML
- let rightMeasureNumberXML = state.section[1].MeasureNumberXML
- if (leftMeasureNumberXML > rightMeasureNumberXML) {
- leftMeasureNumberXML = state.section[1].MeasureNumberXML
- rightMeasureNumberXML = state.section[0].MeasureNumberXML
- }
- state.vfmeasures.forEach((item: any, idx: number) => {
- const dataNum = item.getAttribute('data-num')
- let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
- let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
-
- if(!(nextDataNum && nextDataNum !== "undefined")){
- nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
- }
- const nextMeasureNum = Number(nextDataNum)
-
- if(measureNum === -1) {
- measureNum = nextMeasureNum
- }
-
- if (measureNum < leftMeasureNumberXML) {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", 'transparent')
- }
-
- if(measureNum > rightMeasureNumberXML){
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", 'transparent')
- }
- if (measureNum >= leftMeasureNumberXML && measureNum <= rightMeasureNumberXML) {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(9,159,255,0.15)")
- }
-
- if(state.sectionFirst && measureNum === state.sectionFirst.MeasureNumberXML){
- item?.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(255,193,48,0.15)")
- }
- })
- }else{
-
- state.vfmeasures.forEach((item: any, idx: number) => {
- const dataNum = item.getAttribute('data-num')
- let measureNum = (dataNum && dataNum !== "undefined") ? Number(dataNum) : -1;
- let nextDataNum = state.vfmeasures[idx+1]?.getAttribute('data-num')
-
- if(!(nextDataNum && nextDataNum !== "undefined")){
- nextDataNum = state.vfmeasures[idx + 2]?.getAttribute('data-num')
- }
- const nextMeasureNum = Number(nextDataNum)
-
- if(measureNum === -1) {
- measureNum = nextMeasureNum
- }
- if (measureNum >= 0 && (measureNum === state.activeMeasureIndex || (measureNum < state.activeMeasureIndex && nextMeasureNum > state.activeMeasureIndex)) ) {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(9,159,255,0.15)")
- } else {
- item.querySelector('.vf-custom-bg')?.setAttribute("fill", "transparent")
- }
- })
- }
- }
- )
- export const checkMoveNoSave = async () => {
- return new Promise((resolve, reject) => {
- if (query.isMove) {
- if (moveData.open && undoData.undoList.length) {
- showConfirmDialog({
- className: "noSaveModal",
- title: "温馨提示",
- message: "您有新的修改还未保存,切换谱面后本次编辑的内容将不会保存",
- }).then(() => {
- moveData.open = false
- resolve(true)
- }).catch(() => {
- return;
- });
- } else {
- moveData.open = false
- undoData.undoList = []
- resolve(true)
- }
- } else {
- resolve(true)
- }
- });
- }
- export const refreshMusicSvg = () => {
- (window as any).DYhideTrackTune = false;
- moveData.noteCoords = []
- moveData.modelList = []
- clearSelection();
- resetBaseRate();
- state.activeMeasureIndex = -1;
- if (query.workRecord) {
- state.workSectionNeedReset = true;
- }
-
- destroySmoothAnimation()
- musicScoreRef.value?.refreshMusicScore()
- }
- watch(
- () => state.setting.displayFingering,
- () => {
-
- if(state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && state.isSingleLine){
- nextTick(() => {
- calcClientWidth()
- })
- }
-
- if (state.fingeringInfo?.name && state.fingeringInfo.direction === "vertical" && !state.isSingleLine) {
- headTopData.settingMode = false;
- refreshMusicSvg();
- }
- }
- )
- watch(
- () => headTopData.rhythmMode,
- () => {
-
- if(headTopData.rhythmModeDirection === "vertical" && state.isSingleLine){
- nextTick(() => {
- calcClientWidth()
- })
- }
-
- if (headTopData.rhythmModeDirection === "vertical" && !state.isSingleLine) {
- refreshMusicSvg();
- }
- }
- )
|