index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import { defineComponent, onMounted, onUnmounted, reactive, ref, watch } from "vue";
  2. import state, { gotoNext, resetPlaybackToStart, followBeatPaly, skipNotePlay, initSetPlayRate } from "/src/state";
  3. import { IPostMessage } from "/src/utils/native-message";
  4. import { api_cloudFollowTime, api_cloudToggleFollow } from "/src/helpers/communication";
  5. import { storeData } from "/src/store";
  6. import { audioRecorder } from "./audioRecorder";
  7. import { handleStartTick } from "/src/view/tick";
  8. import { metronomeData } from "/src/helpers/metronome";
  9. import { getDuration } from "/src/helpers/formateMusic";
  10. import { OpenSheetMusicDisplay } from "/osmd-extended/src";
  11. import { browser, getBehaviorId } from "/src/utils";
  12. import { api_musicPracticeRecordSave } from "../../page-instrument/api";
  13. import { getQuery } from "/src/utils/queryString";
  14. const query: any = getQuery();
  15. export const followData = reactive({
  16. list: [] as any, // 频率列表
  17. index: 0,
  18. start: false,
  19. rendered: false,
  20. /** 麦克风权限 */
  21. earphone: false,
  22. isBeginMask: false, // 倒计时和系统节拍器时候的遮罩,防止用户点击
  23. dontAccredit: true, // 没有开启麦克风权限,不需要调用结束收音的api
  24. practiceStart: false,
  25. });
  26. // 记录跟练时长
  27. const handleRecord = (total: number) => {
  28. if (query.isCbs) return
  29. if (total < 0) total = 0;
  30. const totalTime = total / 1000;
  31. const body = {
  32. clientType: storeData.user.clientType,
  33. musicSheetId: state.examSongId,
  34. sysMusicScoreId: state.examSongId,
  35. feature: "FOLLOW_UP_TRAINING",
  36. practiceSource: "FOLLOW_UP_TRAINING",
  37. playTime: totalTime,
  38. deviceType: browser().android ? "ANDROID" : "IOS",
  39. behaviorId: getBehaviorId(),
  40. };
  41. api_musicPracticeRecordSave(body);
  42. };
  43. /** 点击跟练模式 */
  44. export const toggleFollow = (notCancel = true) => {
  45. state.modeType = state.modeType === "follow" ? "practise" : "follow";
  46. // 取消跟练
  47. if (!notCancel) {
  48. followData.start = false;
  49. followData.practiceStart = false;
  50. // 开启了麦克风授权,才需要调用结束收音
  51. if (storeData.isApp && !followData.dontAccredit) {
  52. openToggleRecord(false);
  53. }
  54. }
  55. };
  56. const noteFrequency = ref(0);
  57. const audioFrequency = ref(0);
  58. const followTime = ref(0);
  59. // 切换录音
  60. const openToggleRecord = async (open: boolean = true) => {
  61. if (!open) api_cloudToggleFollow(open ? "start" : "end");
  62. // 记录跟练时长
  63. if (open) {
  64. followTime.value = Date.now();
  65. } else {
  66. const playTime = Date.now() - followTime.value;
  67. if (followTime.value !== 0 && playTime > 0) {
  68. handleRecord(playTime);
  69. followTime.value = 0;
  70. }
  71. }
  72. if (!storeData.isApp) {
  73. const openState = await audioRecorder?.toggleRecord(open);
  74. // 开启录音失败
  75. if (!openState && followData.start) {
  76. followData.earphone = true;
  77. followData.start = false;
  78. followData.practiceStart = false;
  79. }
  80. }
  81. };
  82. // 清除音符状态
  83. const onClear = () => {
  84. state.times.forEach((item: any) => {
  85. const note: HTMLElement = document.querySelector(`div[data-vf=vf${item.id}]`)!;
  86. if (note) {
  87. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  88. }
  89. const _note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  90. const stemEl = document.getElementById(`vf-${item.id}-stem`);
  91. if (_note) {
  92. _note.classList.remove("follow-up", "follow-down", "follow-success");
  93. stemEl?.classList.remove("follow-up", "follow-down", "follow-success");
  94. }
  95. });
  96. };
  97. /** 开始跟练 */
  98. export const handleFollowStart = async () => {
  99. followData.isBeginMask = true
  100. checking = false;
  101. const res = await api_cloudToggleFollow("start");
  102. // 用户没有授权,需要重置状态
  103. if (res?.content?.reson) {
  104. followData.isBeginMask = false
  105. followData.start = false;
  106. followData.practiceStart = false;
  107. } else {
  108. followData.dontAccredit = false;
  109. // 跟练模式开始前,增加播放系统节拍器
  110. const tickend = await handleStartTick();
  111. // console.log("🚀 ~ tickend:", tickend)
  112. // 节拍器返回false, 取消播放
  113. if (!tickend) {
  114. followData.isBeginMask = false
  115. followData.start = false;
  116. followData.practiceStart = false;
  117. return false;
  118. }
  119. onClear();
  120. followData.isBeginMask = false
  121. followData.start = true;
  122. followData.practiceStart = true;
  123. followData.index = 0;
  124. followData.list = [];
  125. initSetPlayRate();
  126. resetPlaybackToStart();
  127. openToggleRecord(true);
  128. getNoteIndex();
  129. const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
  130. metronomeData.totalNumerator = duration.numerator || 2
  131. metronomeData.followAudioIndex = 1
  132. state.beatStartTime = 0
  133. followBeatPaly();
  134. }
  135. };
  136. /** 结束跟练 */
  137. export const handleFollowEnd = () => {
  138. onClear();
  139. followData.start = false;
  140. followData.practiceStart = false;
  141. openToggleRecord(false);
  142. followData.index = 0;
  143. console.log("结束");
  144. };
  145. // 清除当前音符右侧的音符的颜色状态
  146. const clearRightNoteColor = () => {
  147. const noteId = state.times[state.activeNoteIndex]?.id;
  148. const leftVal = document.getElementById(`vf-${noteId}`)?.getBoundingClientRect()?.left || 0;
  149. state.times.forEach((item: any) => {
  150. const note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  151. if (note?.getBoundingClientRect()?.left >= leftVal) {
  152. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  153. }
  154. });
  155. }
  156. /**
  157. * 2024.6.17 新增自动结束跟练模式功能
  158. * 如果跟练模式,唱完了最后一个有频率的音符,需要自动结束掉跟练模式
  159. * 需要判断当前音符的后面是否都是休止音符(休止音符的频率都是-1),或者是否是最后一个音符了
  160. */
  161. const autoEndFollow = () => {
  162. if (followData.index >= state.times.length) {
  163. handleFollowEnd()
  164. return
  165. }
  166. let nextIndex = followData.index + 1;
  167. const rightTimes = state.times.slice(followData.index,state.times.length)
  168. // 后面的音符是否都是休止音符
  169. const isAllRest = !rightTimes.some((item: any) => item.frequency > 1);
  170. if (isAllRest && state.times[followData.index].frequency < 1) {
  171. handleFollowEnd()
  172. return
  173. }
  174. clearRightNoteColor();
  175. }
  176. // 下一个
  177. const next = () => {
  178. if (followData.index < state.times.length) {
  179. gotoNext(state.times[followData.index]);
  180. }
  181. autoEndFollow();
  182. };
  183. // 获取当前音符
  184. const getNoteIndex = (): any => {
  185. const item = state.times[followData.index];
  186. if (item.frequency <= 0) {
  187. followData.index = followData.index + 1;
  188. next();
  189. return getNoteIndex();
  190. }
  191. noteFrequency.value = item.frequency;
  192. // state.fixedKey = item.realKey;
  193. return {
  194. id: item.id,
  195. min: item.frequency - (item.frequency - item.prevFrequency) * 0.5,
  196. max: item.frequency + (item.nextFrequency - item.frequency) * 0.5,
  197. duration: item.duration,
  198. baseFrequency: item.frequency,
  199. };
  200. };
  201. let checking = false;
  202. /** 录音回调 */
  203. const onFollowTime = (evt?: IPostMessage) => {
  204. const frequency: number = evt?.content?.frequency;
  205. // 没有开始, 不处理
  206. if (!followData.start) return;
  207. // console.log('频率', frequency)
  208. if (frequency > 0) {
  209. audioFrequency.value = frequency;
  210. // data.list.push(frequency)
  211. checked();
  212. }
  213. };
  214. let startTime = 0;
  215. const checked = () => {
  216. if (checking) return;
  217. checking = true;
  218. const item = getNoteIndex();
  219. // 降噪处理, 频率低于 当前音的50% 时, 不处理
  220. if (audioFrequency.value < item.baseFrequency * 0.5) {
  221. checking = false;
  222. return;
  223. }
  224. if (audioFrequency.value >= item.min && audioFrequency.value <= item.max) {
  225. if (startTime === 0) {
  226. startTime = Date.now();
  227. } else {
  228. const playTime = (Date.now() - startTime) / 1000;
  229. // console.log('时长', playTime, item.duration / 2)
  230. if (playTime >= item.duration * 0.6) {
  231. startTime = 0;
  232. followData.index = followData.index + 1;
  233. setColor(item, "", true);
  234. setTimeout(() => {
  235. next();
  236. checking = false;
  237. }, 3000);
  238. return;
  239. }
  240. }
  241. // console.log("频率对了", item.min, audioFrequency.value, item.max, item.duration);
  242. }
  243. // console.log("频率不对", item.min, audioFrequency.value, item.max, item.baseFrequency);
  244. setColor(item, audioFrequency.value > item.baseFrequency ? "follow-up" : "follow-down");
  245. checking = false;
  246. };
  247. const setColor = (item: any, state: "follow-up" | "follow-down" | "", isRight = false) => {
  248. const note: HTMLElement = document.querySelector(`div[data-vf=vf${item.id}]`)!;
  249. if (note) {
  250. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  251. if (isRight) {
  252. note.classList.add("follow-success");
  253. } else {
  254. note.classList.add("follow-error", state);
  255. }
  256. }
  257. const _note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  258. if (_note) {
  259. const stemEl = document.getElementById(`vf-${item.id}-stem`)
  260. _note.classList.remove("follow-up", "follow-down");
  261. stemEl?.classList.remove("follow-up", "follow-down","follow-success");
  262. if (state) {
  263. _note.classList.add(state);
  264. stemEl?.classList.add(state)
  265. }
  266. if (isRight) {
  267. _note.classList.add("follow-success");
  268. stemEl?.classList.add("follow-success")
  269. }
  270. }
  271. };
  272. // 进度跟练,点击某个音符开始跟练
  273. export const skipNotePractice = () => {
  274. followData.index = state.activeNoteIndex
  275. // 清除其它音符的错误提示
  276. const noteFollows: HTMLElement[] = Array.from(document.querySelectorAll(".follow-error"));
  277. noteFollows.forEach((noteFollow) => {
  278. noteFollow?.classList.remove("follow-up", "follow-down", "follow-error");
  279. })
  280. clearRightNoteColor();
  281. }
  282. // 移动到对应音符的位置
  283. watch(
  284. () => followData.index,
  285. () => {
  286. skipNotePlay(followData.index);
  287. }
  288. );
  289. export default defineComponent({
  290. name: "follow",
  291. setup() {
  292. onMounted(async () => {
  293. /** 如果是PC端 */
  294. if (!storeData.isApp) {
  295. const canRecorder = await audioRecorder.checkSupport();
  296. if (canRecorder) {
  297. audioRecorder.init();
  298. audioRecorder.progress = (frequency: number) => {
  299. onFollowTime({ api: "", content: { frequency } });
  300. };
  301. } else {
  302. followData.earphone = true;
  303. }
  304. } else {
  305. api_cloudFollowTime(onFollowTime);
  306. }
  307. console.log("进入跟练模式");
  308. });
  309. onUnmounted(() => {
  310. // api_cloudFollowTime(onFollowTime, false);
  311. resetPlaybackToStart();
  312. onClear();
  313. // 开启了麦克风授权,才需要调用结束收音
  314. if (storeData.isApp && !followData.dontAccredit) {
  315. openToggleRecord(false);
  316. }
  317. console.log("退出跟练模式");
  318. });
  319. return () => <div></div>;
  320. },
  321. });