use-app.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { onBeforeUnmount, onMounted, Ref, ref, watch } from 'vue'
  2. import { useClientType, useOriginSearch } from '.'
  3. import request from '/src/helpers/request'
  4. import originRequest from 'umi-request'
  5. import store from 'store'
  6. import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
  7. import detailState, { GradualTimes, isRhythmicExercises } from '/src/pages/detail/state'
  8. import SettingState from '/src/pages/detail/setting-state'
  9. import { listenerMessage, postMessage } from '/src/helpers/native-message'
  10. import audiosInstance from '/src/helpers/multiple-audio'
  11. import { formatXML, onlyVisible, getCustomInfo } from '/src/pages/detail/helpers'
  12. import { MusicSheelDetail, ShaeetStatusType } from '../index.d'
  13. import { browser, getRequestHostname, isEncoded, setGlobalData } from '/src/helpers/utils'
  14. import formatId, { formatdata, getSubjectIdCode } from '../fingering/format-id'
  15. import { evaluatStopPlay } from '../buttons/evaluating'
  16. import state from '/src/pages/detail/state'
  17. import { getGradualLengthByXml } from '/src/pages/detail/calcSpeed'
  18. import { musicInfo } from '../state'
  19. import { getInstrumentName } from '../helpers/instruments'
  20. const search = useOriginSearch()
  21. const skpList = ['Ukulele']
  22. /**
  23. * 特殊教材分类id
  24. */
  25. export const classids = [1, 2, 6, 7, 8, 9, 3, 10, 11, 12, 13, 4, 14, 15, 16, 17, 30, 31, 35, 36, 108]; // 大雅金唐, 竖笛教程, 声部训练展开的分类ID
  26. // export const classids = [1, 30, 97]; // [大雅金唐, 竖笛教程, 声部训练]
  27. /**
  28. * 获取xml并前置格式化
  29. * @param url xml地址
  30. * @param detail 音乐详情
  31. * @returns Ref<string>
  32. */
  33. export const useXml = async (url: string, detail: MusicSheelDetail) => {
  34. const partIndex = Number(search['part-index']) || 0
  35. let score = ref<string>('')
  36. try {
  37. const xml = await originRequest(url)
  38. const parseXmlInfo = getCustomInfo(xml)
  39. if (skpList.includes(parseXmlInfo.code)) {
  40. score.value = xml
  41. } else {
  42. score.value = formatXML(parseXmlInfo.parsedXML, {
  43. title: detail.musicSheetName,
  44. })
  45. // 多种乐器分轨合并显示
  46. if (state.isCombineRender) {
  47. setGlobalData('wrapNum', 4)
  48. } else {
  49. score.value = onlyVisible(score.value, partIndex)
  50. }
  51. state.partIndex = partIndex
  52. }
  53. state.gradual = getGradualLengthByXml(xml)
  54. } catch (error) {}
  55. return score
  56. }
  57. /**
  58. * 设置音频信息
  59. * @param detail 音乐详情
  60. */
  61. export const useMp3s = async (detail: MusicSheelDetail) => {
  62. const search = useOriginSearch()
  63. const partIndex = ((search['part-index'] as string) || 0) as unknown as number
  64. const activebg = detail.background?.[partIndex]
  65. Object.assign(musicInfo, activebg)
  66. if (musicInfo.musicSvg) {
  67. try {
  68. musicInfo.musicSvg = typeof musicInfo.musicSvg === 'string' && musicInfo.musicSvg ? JSON.parse(musicInfo.musicSvg) : ''
  69. } catch (error) {}
  70. }
  71. // 伴奏
  72. const backgroundSong = isEncoded(detail.metronomeUrl || '') ? detail.metronomeUrl || '' : encodeURI(detail.metronomeUrl || '')
  73. // 原音
  74. const musicSong = isEncoded(activebg?.audioFileUrl|| '') ? activebg?.audioFileUrl || '' : encodeURI(activebg?.audioFileUrl|| '')
  75. // 兼容未修改之前
  76. runtime.songs = {
  77. background: backgroundSong ? backgroundSong + '?t=background' : '',
  78. music: musicSong ? musicSong + '?t=music' : '',
  79. }
  80. detailState.isAppPlay = detail.audioType === 'MIDI'
  81. let defaultExtConfigJson = {
  82. skipTick: false,
  83. repeatedBeats: false,
  84. scoreSize: 'middle',
  85. }
  86. let extConfigJson = {}
  87. detailState.activeDetail = {
  88. ...detail,
  89. examSongId: detail.id,
  90. originalSpeed: 90,
  91. isAppPlay: detail.audioType === 'MIDI',
  92. extConfigJson: {
  93. ...defaultExtConfigJson,
  94. },
  95. }
  96. detailState.isPercussion = musicInfo.musicSubject == '1' || isRhythmicExercises();
  97. try {
  98. extConfigJson = JSON.parse(detail?.extConfigJson || '')
  99. } catch (error) {}
  100. detailState.activeDetail.extConfigJson = {
  101. ...detailState.activeDetail.extConfigJson,
  102. ...extConfigJson,
  103. }
  104. const setZoom = detailState.activeDetail.extConfigJson.scoreSize
  105. const zooms = store.get('zooms') || {}
  106. if (setZoom && !zooms['' + detail.id]) {
  107. store.set('zooms', { ...zooms, ['' + detail.id]: setZoom })
  108. SettingState.sett.scoreSize = setZoom
  109. }
  110. detailState.needTick = (detail.audioType === 'MP3' && detail.mp3Type === 'MP3' && detail.musicSheetType != 'CONCERT' ) || detail.audioType === 'MIDI'
  111. detailState.skipTick = detailState.activeDetail.extConfigJson.skipTick
  112. detailState.repeatedBeats = detailState.activeDetail.extConfigJson.repeatedBeats
  113. if (!runtime.songs['music']) {
  114. RuntimeUtils.changeMode('background')
  115. }
  116. // console.log({ ...detailState.activeDetail })
  117. if (!runtime.audiosInstance) {
  118. runtime.audiosInstance = new audiosInstance(Object.values(runtime.songs) as string[])
  119. }
  120. }
  121. /**
  122. * 获取异形屏信息
  123. * @returns {Promise<void>}
  124. */
  125. export const useSpecialShapedScreen = () => {
  126. const heightRef = ref<number>(0)
  127. postMessage(
  128. {
  129. api: 'isSpecialShapedScreen',
  130. },
  131. (evt) => {
  132. const height = evt?.content.notchHeight
  133. detailState.notchHeight =
  134. (browser().ios ? height * 2 : height) || (evt?.content.isSpecialShapedScreen && browser().ios ? 100 : 0)
  135. heightRef.value = detailState.notchHeight
  136. detailState.isSpecialShapedScreen = evt?.content.isSpecialShapedScreen
  137. document.documentElement.style.setProperty('--popup-loading', detailState.notchHeight / 4 + 'px')
  138. }
  139. )
  140. return [heightRef]
  141. }
  142. /**
  143. * 获取当前曲目信息
  144. * @param id 歌曲id
  145. */
  146. export const useDetail = (id: number | string): [Ref<ShaeetStatusType>, Ref<MusicSheelDetail>] => {
  147. const prefix = getRequestHostname()
  148. const status = ref<ShaeetStatusType>('loading')
  149. const data = ref<MusicSheelDetail>({})
  150. status.value = 'loading'
  151. request
  152. .get(`/musicSheet/detail/${id}`, {
  153. prefix: prefix,
  154. })
  155. .then((res) => {
  156. useMp3s(res.data)
  157. data.value = {
  158. ...res.data,
  159. code:
  160. Array.isArray(res?.data?.background) && res.data.background.length
  161. ? getSubjectIdCode(res.data.background[0].musicSubject)
  162. : '',
  163. }
  164. // notation: 是能转简谱 0: 不可以,需要设置成五线谱模式, 是否是切换简谱
  165. if (data.value.notation == 0 || !sessionStorage.getItem('notation')) {
  166. SettingState.sett.type = 'staff'
  167. }
  168. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  169. detailState.isSpecialBookCategory = !classids.includes(res.data.musicSheetCategoriesId)
  170. detailState.subjectId = Number(musicInfo.musicSubject)
  171. // 打击乐声部下的曲目,需要合并展示所有分轨
  172. if (Number(res.data.musicSubject) === 1 && res.data.background?.length > 1) {
  173. state.isCombineRender = true
  174. // 开启自定义每行显示的小节数
  175. ;(window as any).customSectionAmount = true
  176. setGlobalData('multitrack', res.data.background?.length)
  177. }
  178. ;(window as any).DYSubjectId = formatId(data.value.code as any)
  179. ;(window as any).DYMusicSheetId = Number(id)
  180. status.value = 'success'
  181. // 额外配置
  182. let extConfigJson = {
  183. gradualTimes: {},
  184. }
  185. try {
  186. if (data.value?.extConfigJson) {
  187. extConfigJson = {
  188. ...extConfigJson,
  189. ...JSON.parse(data.value.extConfigJson),
  190. }
  191. }
  192. } catch (error) {}
  193. state.gradualTimes = extConfigJson.gradualTimes as GradualTimes
  194. // 合奏设置
  195. if (res?.data?.musicSheetType == 'CONCERT') {
  196. const backgrounds = res?.data?.background || [];
  197. const partIndex = Number(search['part-index']) || 0
  198. let track = backgrounds[partIndex]?.track
  199. if (backgrounds[0]?.track?.toLocaleUpperCase() == 'COMMON'){
  200. track = backgrounds[partIndex + 1]?.track
  201. }
  202. const instrumentName = getInstrumentName(track)
  203. console.log("🚀 ~ track:", track)
  204. detailState.partName = track + (instrumentName ? `(${instrumentName})` : '')
  205. const _track = Object.keys(formatdata).filter((key) => key.includes(track) || track.includes(key))[0]
  206. data.value.code = _track
  207. }
  208. })
  209. .catch(() => (status.value = 'error'))
  210. return [status, data]
  211. }
  212. /**
  213. * 监听后台切换状态,暂停播放与评测
  214. */
  215. export const useSuspendPlay = () => {
  216. listenerMessage('suspendPlay', () => {
  217. if (detailState.activeTick > -1) {
  218. RuntimeUtils.stopTick()
  219. }
  220. console.log(runtime.playState)
  221. if (runtime.playState === 'play') {
  222. RuntimeUtils.resetPlayStatus()
  223. if (runtime.evaluatingStatus) {
  224. // postMessage(
  225. // {
  226. // api: 'pauseRecording',
  227. // },
  228. // () => {
  229. // detailState.isPauseRecording = true
  230. // }
  231. // )
  232. evaluatStopPlay()
  233. }
  234. }
  235. })
  236. }