Files
zyt/TUICallKit-Vue3/hooks/useMetronome.ts
T
longandCursor 2beace89f4 feat(TUICallKit-Vue3): 迁入节拍器与练一练训练模块
之前误将训练模块加在 uniapp 项目,实际目标项目是 TUICallKit-Vue3
(甄养堂主小程序壳),整体迁入:

- hooks/useMetronome.ts  节拍器(音频实例池+预热,无冷启动延迟)
- hooks/useTrainingSession.ts  训练 Session 状态机
- hooks/useVoiceCoach.ts  语音教练队列
- hooks/useTrainingBgm.ts  训练/休息 BGM 切换+渐变
- pages/training/index.vue  练一练主页(器械跟练)
- pages/training/metronome.vue  独立节拍器(老人友好版,
  中央圆即开始/暂停按钮,纯 CSS 几何 icon,大字大按钮)
- pages/training/components/exercise-anim.vue  CSS 动作动画
- pages/training/exercises.ts  5 个器械动作预设
- static/training/audio/*.mp3  3 种 click 音色(MIT 协议)
- scripts/generate-voice.mjs  MiMo TTS 批量生成语音脚本
- pages.json 注册 pages/training/index 与 pages/training/metronome
- 「我的」页加 DevTrainingEntry 悬浮入口,生产环境自动隐藏

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 11:28:55 +08:00

206 lines
5.1 KiB
TypeScript

import { ref, computed, onUnmounted } from 'vue'
export interface MetronomeOptions {
initialBpm?: number
bpmMin?: number
bpmMax?: number
clickSrc?: string
accentSrc?: string
accentEvery?: number
poolSize?: number
onBeat?: (beatIndex: number, isAccent: boolean) => void
}
/**
* 音频实例池:每个 click 用一个独立 InnerAudioContext,循环复用。
* 解决两个问题:
* 1. seek+play 模式在某些设备上首拍冷启动延迟(100-300ms)
* 2. BPM 偏快时上一拍音频还没播完,下一拍 play 会被阻塞或丢失
*/
class AudioPool {
private list: UniApp.InnerAudioContext[] = []
private cursor = 0
private warmedUp = false
constructor(
private src: string,
private size: number,
) {}
private create() {
for (let i = 0; i < this.size; i++) {
const ctx = uni.createInnerAudioContext()
ctx.src = this.src
ctx.obeyMuteSwitch = false
ctx.autoplay = false
this.list.push(ctx)
}
}
/**
* 预热:静音播放一次每个实例,让音频解码完成
* 这样后续 play() 时就是热启动,没有冷启动延迟
*/
warmUp() {
if (this.warmedUp) return
if (this.list.length === 0) this.create()
this.list.forEach((ctx) => {
const originalVolume = ctx.volume
ctx.volume = 0
try {
ctx.play()
setTimeout(() => {
try {
ctx.stop()
ctx.volume = originalVolume === 0 ? 1 : originalVolume
} catch (_) {}
}, 80)
} catch (_) {}
})
this.warmedUp = true
}
play() {
if (this.list.length === 0) {
this.create()
this.warmUp()
}
const ctx = this.list[this.cursor]
this.cursor = (this.cursor + 1) % this.list.length
try {
ctx.seek(0)
ctx.play()
} catch (_) {
ctx.play()
}
}
destroy() {
this.list.forEach((ctx) => {
try {
ctx.destroy?.()
} catch (_) {}
})
this.list = []
this.warmedUp = false
}
}
export function useMetronome(options: MetronomeOptions = {}) {
const {
initialBpm = 80,
bpmMin = 40,
bpmMax = 240,
clickSrc = '/static/training/audio/click.mp3',
accentSrc,
poolSize = 4,
onBeat,
} = options
const bpm = ref<number>(initialBpm)
const isPlaying = ref<boolean>(false)
const beatIndex = ref<number>(0)
const isAccent = ref<boolean>(false)
const accentEveryRef = ref<number>(options.accentEvery ?? 4)
const intervalMs = computed(() => 60000 / bpm.value)
let clickPool: AudioPool | null = null
let accentPool: AudioPool | null = null
let timer: ReturnType<typeof setTimeout> | null = null
let nextTickAt = 0
const ensureAudio = () => {
if (!clickPool) {
clickPool = new AudioPool(clickSrc, poolSize)
clickPool.warmUp()
}
if (accentSrc && !accentPool) {
accentPool = new AudioPool(accentSrc, Math.max(2, Math.ceil(poolSize / 2)))
accentPool.warmUp()
}
}
const playSound = (accent: boolean) => {
if (accent && accentPool) {
accentPool.play()
} else if (clickPool) {
clickPool.play()
}
}
const tick = () => {
if (!isPlaying.value) return
const every = Math.max(1, accentEveryRef.value)
const accent = beatIndex.value % every === 0
isAccent.value = accent
playSound(accent)
onBeat?.(beatIndex.value, accent)
beatIndex.value++
nextTickAt += intervalMs.value
const drift = Date.now() - nextTickAt
const nextDelay = Math.max(0, intervalMs.value - drift)
timer = setTimeout(tick, nextDelay)
}
const start = () => {
if (isPlaying.value) return
ensureAudio()
isPlaying.value = true
beatIndex.value = 0
nextTickAt = Date.now()
tick()
}
const stop = () => {
isPlaying.value = false
if (timer) {
clearTimeout(timer)
timer = null
}
}
const setBpm = (val: number) => {
bpm.value = Math.max(bpmMin, Math.min(bpmMax, Math.round(val)))
}
const setAccentEvery = (n: number) => {
accentEveryRef.value = Math.max(1, Math.min(16, Math.round(n)))
beatIndex.value = 0
}
/**
* 主动预加载(推荐在页面 onShow 时调用,让用户进页面就完成预热)
*/
const preload = () => {
ensureAudio()
}
onUnmounted(() => {
stop()
clickPool?.destroy()
accentPool?.destroy()
clickPool = null
accentPool = null
})
return {
bpm,
isPlaying,
beatIndex,
isAccent,
intervalMs,
accentEvery: accentEveryRef,
start,
stop,
setBpm,
setAccentEvery,
preload,
}
}