音频练习由两个页面组成:列表页用竖向 Tab 分好类、只持数据,详情页只负责把一条音频播出来。
两页之间没有共享状态,全靠 eventCenter 传两类消息——列表推「播哪一条」,详情发「上一首 / 下一首」指令。
InnerAudioContext 是事件驱动的 API,duration 与 currentTime 都必须先「读一次」才会带出真实值,这是本页最反直觉的地方。
第四节集中修正五处已知问题:首屏事件丢失、监听器累积、pause / stop 混用、currentTime 越界、时长换算单位。
一、整体结构(列表页 ↔ 详情页)
1.1 两个页面各管什么
| 页面 |
文件 |
职责 |
| 列表页 |
src/subA/pages/audio/audioT.tsx |
持有 columnList(唯一数据源)、渲染竖向 Tab、计算相邻下标 |
| 详情页 |
src/subA/pages/audio/audioTDetail.tsx |
持有 InnerAudioContext、渲染播放条、发出 prev / next 指令 |
| 事件常量 |
src/subA/pages/env.ts |
集中声明跨页事件名 |
| 时间工具 |
src/utils/date.ts |
补零与秒数格式化 |
职责划分只有一条原则:『列表页持有数据,详情页只负责播』。详情页不关心「下一首是谁」,它只发一个 'next';换哪条、下标怎么绕回,全在列表页算。数据源始终只有一份,两页就不会出现状态不一致。
1.2 数据结构
1 2
| type AudioItem = { id: number; voiceUrl: string } type Column = { title: string; subList: AudioItem[] }
|
列表页把六组数据放进一个 useState,只在初始化时赋值,之后不再改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const [currentIndex, setCurrentIndex] = useState(0) const [columnList] = useState<Column[]>([ { title: '标签页1', subList: [ { id: 1, voiceUrl: 'https://.../43041460-....mp3' }, { id: 2, voiceUrl: 'https://.../31035e0c-....mp3' }, ], }, { title: '标签页2', subList: [] }, { title: '标签页3', subList: [] }, { title: '标签页4', subList: [] }, { title: '标签页5', subList: [] }, { title: '标签页6', subList: [] }, ])
|
1.3 一次完整交互的数据流
1 2 3 4 5 6 7 8 9 10 11
| 列表页 详情页 │ ① 点条目:记下游标 (outIndex, index) │ navigateTo('./audioTDetail') │ │ ② 详情页挂载 → 注册 LISTTODETAIL │ ◀── trigger(DETAILREADY, { outIndex, index }) │ ── trigger(LISTTODETAIL, { data }) ──▶ 设置 src,开始播 │ │ ③ 用户点「下一首」/ 播放自然结束 │ ◀── trigger(DETAILTOLIST, 'next') │ 算出新下标 → trigger(LISTTODETAIL, newData) ──▶ 换源,继续播
|
②是「握手」:详情页先说自己监听好了,列表页再推首条数据。为什么必须这样做,见 4.1。
二、跨页通信:eventCenter + 事件常量 + useUnload 清理
2.1 为什么选 eventCenter
小程序没有 Vue Router 那样的路由参数传对象、也没有全局 store 可直接用,跨页通信常见的三种做法:
| 方案 |
成本 |
适合 |
eventCenter |
最低,十几行 |
消息少、单向指令、数据量小 |
全局状态(如 @tanstack/react-query 缓存 / 自建 store) |
中,要设计数据结构 |
多页共享同一份数据 |
getCurrentPages() 拿上一页实例直接调方法 |
低但耦合强 |
临时应急,不建议长期 |
这里只有「播哪条」和「上一首 / 下一首」两种消息,eventCenter 是最轻的一套,成本低、够用,值得作为团队约定。
2.2 事件常量集中管理
src/subA/pages/env.ts:
1 2 3
| export const LISTTODETAIL = 'LISTTODETAIL' export const DETAILTOLIST = 'DETAILTOLIST' export const DETAILREADY = 'DETAILREADY'
|
『事件名抽成常量,是这套方案能维护的前提』。直接写字符串的话,跨页通信会变成「谁也不知道有哪些事件」的黑盒,改一个名字要全项目搜字符串。
2.3 列表页:发首条数据、算相邻下标
点击时只记游标并跳转,不在这里注册任何监听:
1 2 3 4 5 6 7
| const columnListRef = useRef(columnList) const cursorRef = useRef({ outIndex: 0, index: 0 })
const goAudioDetail = (outIndex: number, index: number) => { cursorRef.current = { outIndex, index } navigateTo({ url: './audioTDetail' }) }
|
监听统一放在页面「显示」时注册、「隐藏」时解除:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| useDidShow(() => { const handleReady = () => { const { outIndex, index } = cursorRef.current eventCenter.trigger(LISTTODETAIL, { data: columnListRef.current[outIndex].subList[index], }) }
const handleCommand = (action: 'prev' | 'next') => { const { outIndex, index } = cursorRef.current const list = columnListRef.current[outIndex].subList const length = list.length if (length === 0) return
const nextIndex = action === 'prev' ? (index - 1 + length) % length : (index + 1) % length
cursorRef.current = { outIndex, index: nextIndex } eventCenter.trigger(LISTTODETAIL, { data: list[nextIndex] }) }
eventCenter.on(DETAILREADY, handleReady) eventCenter.on(DETAILTOLIST, handleCommand) })
useDidHide(() => { eventCenter.off(DETAILREADY) eventCenter.off(DETAILTOLIST) })
|
两个细节:
- 循环边界用取模一次写完:
(index - 1 + length) % length 和 (index + 1) % length 比两段三元表达式更难写错,+ length 是为了避免 JS 里 -1 % 5 === -1。
- **游标用
useRef 而不是 useState**:它只在回调里读写、不参与渲染,进 state 会多一次无意义的重渲染,还可能让回调读到过期值。
列表渲染仍在列表页,AtTabs 负责竖向分类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <AtTabs current={currentIndex} scroll height="800px" tabDirection="vertical" tabList={columnList.map(item => ({ title: item.title }))} onClick={(e: number) => setCurrentIndex(e)} > {columnList.map((outItem, outIndex) => ( <AtTabsPane key={outIndex} tabDirection="vertical" current={currentIndex} index={outIndex}> <View className="flex flex-col h-screen items-center"> {outItem.subList.length > 0 ? ( outItem.subList.map((item, index) => ( <View key={item.id} className="h-[100px] w-full border-2 solid my-10 mx-5" onTap={() => goAudioDetail(outIndex, index)} > {item.id} </View> )) ) : ( <View className="py-100 text-[gray]">暂无数据</View> )} </View> </AtTabsPane> ))} </AtTabs>
|
2.4 详情页:注册监听 + 发起握手
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const router = useRouter() const outIndex = Number(router.params.outIndex ?? 0) const index = Number(router.params.index ?? 0)
useEffect(() => { const handleData = (payload: { data: AudioItem }) => setAcceptData(payload.data)
eventCenter.on(LISTTODETAIL, handleData) eventCenter.trigger(DETAILREADY, { outIndex, index })
return () => { eventCenter.off(LISTTODETAIL) } }, [])
|
依赖数组必须是 []。这个 effect 只做「注册一次、卸载时解除」,换歌交给 acceptData 变化去驱动,不再重新注册(原因见 4.2)。
2.5 清理时机:分清「卸载」与「隐藏」
小程序的页面栈只做入栈 / 出栈,**进入详情页时列表页只是 hide,并没有 unload**,所以列表页的监听不能指望 useUnload 去清:
| 页面 |
清理时机 |
用什么 |
| 列表页(会被压在栈里) |
每次离开就清,回来再注册 |
useDidHide / useDidShow |
| 详情页(会被返回销毁) |
卸载时清一次 |
useUnload 或 useEffect 的 cleanup |
成对出现的写法最不容易漏:useDidShow 里 on,useDidHide 里 off;详情页 useEffect([]) 里 on,return 里 off。
三、播放器:InnerAudioContext 事件模型、seek、自动连播
3.1 创建实例
1
| const [context] = useState(() => createInnerAudioContext())
|
必须用惰性初始化(传函数)。源码写的是 useState(createInnerAudioContext()),括号在渲染时就执行了,每次重渲染都会新建一个音频实例并泄漏一个,真正的实例只被第一次渲染的那个占位。
3.2 duration 与 currentTime 要先「读一次」
下面几个回调都写在页面挂载时执行的 useEffect([]) 里,只在首次绑一次:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const [max, setMax] = useState(0) const [finTime, setFinTime] = useState('00:00:00') const [startTime, setStartTime] = useState('00:00:00') const [sliderValue, setSliderValue] = useState(0)
context.onCanplay(() => { context.duration setTimeout(() => { setMax(context.duration) setFinTime(formatDuration(context.duration)) }, 1000) })
context.onTimeUpdate(() => { setSliderValue(context.currentTime) setStartTime(formatDuration(context.currentTime)) })
|
『先访问一次 context.duration 做初始化』:不读这一下,后续 onCanplay / onTimeUpdate 可能不触发,值也恒为 0。setTimeout 1000ms 是等元数据解析完的经验值,更稳的做法是在 onTimeUpdate 首次触发时再取时长,或轮询到 duration > 0 为止。
时间格式化统一收在 src/utils/date.ts:
1 2 3 4 5 6 7 8 9 10
| export const handTimeDiff = (val: number) => (val < 10 ? `0${val}` : `${val}`)
export const formatDuration = (seconds: number) => { const total = Math.floor(seconds || 0) const h = Math.floor(total / 3600) const m = Math.floor((total % 3600) / 60) const s = total % 60 return `${handTimeDiff(h)}:${handTimeDiff(m)}:${handTimeDiff(s)}` }
|
3.3 事件模型
InnerAudioContext 没有同步返回值,一切状态都靠回调:
| 事件 |
触发时机 |
本页用途 |
onCanplay |
音频可播放 |
读 duration,初始化总时长 |
onPlay |
开始播放 |
setIsPlay(true) |
onPause |
调用 pause() |
setIsPlay(false) |
onStop |
调用 stop() |
真正的终止,本页不使用 |
onEnded |
自然播放结束 |
发出 next 指令,实现连播 |
onTimeUpdate |
播放进度变化 |
更新进度条与已播放时间 |
onError |
播放出错 |
打日志,便于排查失效链接 |
注意 pause 与 stop 是两个 API、两个事件:pause() 只触发 onPause,只有 stop() 才触发 onStop。混用的后果见 4.3。
3.4 换源与自动连播
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| useEffect(() => { if (!acceptData?.voiceUrl) return context.src = acceptData.voiceUrl context.play() setIsPlay(true) }, [acceptData])
useEffect(() => { const handleEnded = () => { eventCenter.trigger(DETAILTOLIST, 'next') } context.onEnded(handleEnded) return () => { context.offEnded(handleEnded) } }, [])
|
连播链路是一条闭环:onEnded → trigger(DETAILTOLIST, 'next') → 列表页算新下标 → trigger(LISTTODETAIL, newData) → acceptData 变化 → context.src 换源并 play()。详情页全程不知道「下一首」是谁。
3.5 操作栏:一个函数六种行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| type Action = 'play' | 'pause' | 'prev' | 'next' | 'back' | 'front'
const handAudio = (type: Action) => { switch (type) { case 'play': context.play() setIsPlay(true) break case 'pause': context.pause() setIsPlay(false) break case 'prev': eventCenter.trigger(DETAILTOLIST, 'prev') break case 'next': eventCenter.trigger(DETAILTOLIST, 'next') break case 'back': if (!isPlay) { context.play() setIsPlay(true) } context.currentTime = Math.max(0, context.currentTime - 15) break case 'front': if (!isPlay) { context.play() setIsPlay(true) } context.currentTime = Math.min(context.duration || Infinity, context.currentTime + 15) break } }
|
『currentTime 可读可写』:直接赋值就等于 seek,不需要额外调用 seek()。快退 / 快进都必须在赋值前夹取范围(原因见 4.4)。
3.6 进度条:为什么用 Slider 而不是 Progress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const handleSeek = (e: BaseEventOrig<SliderProps.onChangeEventDetail>) => { context.seek(e.detail.value) }
<Slider min={0} max={max} value={sliderValue} className="flex-auto mx-20" activeColor="green" trackSize="3" blockColor="green" blockSize={0} onChange={handleSeek} />
|
源码注释写明了原因:Progress 只有展示能力、不能拖动,只有 Slider 才带 onChange(拖动过程中持续触发)与 onChanging。blockSize={0} 把圆点藏掉,观感就和 Progress 一致了。
seek() 与给 currentTime 赋值等价,前者写在「用户拖动」、后者写在「快进快退」,两种语义分开更易读。
3.7 渲染结构与清理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <View className="flex flex-col items-center"> <View className="w-[500px] h-[500px] bg-tag3 m-50" /> {} <View className="">测试-{acceptData?.id}</View>
<View className="w-full flex items-center text-24 px-20"> <View className="flex-none">{startTime}</View> <Slider min={0} max={max} value={sliderValue} className="flex-auto mx-20" activeColor="green" trackSize="3" blockColor="green" blockSize={0} onChange={handleSeek} /> <View className="flex-none">{finTime}</View> </View>
<View className="flex w-full mt-50 items-center justify-around text-center"> <View className="w-[80px] h-[80px] leading-[80px] rounded-circle border-2" onClick={() => handAudio('back')}>back</View> <View className="w-[100px] h-[100px] leading-[100px] rounded-circle border-2" onClick={() => handAudio('prev')}>prev</View> <View className="w-[120px] h-[120px] leading-[120px] rounded-circle border-2" onClick={() => handAudio(isPlay ? 'pause' : 'play')}>{isPlay ? 'pause' : 'play'}</View> <View className="w-[100px] h-[100px] leading-[100px] rounded-circle border-2" onClick={() => handAudio('next')}>next</View> <View className="w-[80px] h-[80px] leading-[80px] rounded-circle border-2" onClick={() => handAudio('front')}>front</View> </View> </View>
|
圆形按钮用 w-[Npx] h-[Npx] rounded-circle leading-[Npx] 三件套——leading 等于高度就能让文字垂直居中。
卸载时只做两件事:解除监听、销毁实例。
1 2 3 4
| useUnload(() => { eventCenter.off(LISTTODETAIL) context.destroy() })
|
只 pause() 不销毁,页面返回后声音还在,多次进出还会叠加播放。
四、已知问题与修正
4.1 首屏数据在 navigateTo 的 success 里推,事件可能整条丢失
1 2 3 4 5 6 7 8
| navigateTo({ url: './audioTDetail', success: () => { eventCenter.on(DETAILTOLIST, ) eventCenter.trigger(LISTTODETAIL, { data: columnList[outIndex].subList[index] }) }, })
|
1 2 3 4 5 6 7 8 9 10 11 12
|
useEffect(() => { eventCenter.on(LISTTODETAIL, handleData) eventCenter.trigger(DETAILREADY, { outIndex, index }) return () => eventCenter.off(LISTTODETAIL) }, [])
useDidShow(() => { eventCenter.on(DETAILREADY, handleReady) })
|
原因:navigateTo 的 success 只保证「页面已创建并入栈」,不代表子页面的组件已经挂载、useEffect 已经执行。而 eventCenter 是即时的发布订阅,没有缓冲——trigger 时若没有监听者,消息直接丢弃。握手把顺序倒过来,谁准备好了谁说话。
4.2 在 navigateTo 里注册监听、靠 useUnload 清理,监听器会累积
1 2 3 4 5 6 7 8 9
| navigateTo({ url: './audioTDetail', success: () => eventCenter.on(DETAILTOLIST, handleCommand), })
useUnload(() => { eventCenter.off(DETAILTOLIST) })
|
1 2 3 4 5 6 7 8 9 10
| useDidShow(() => { eventCenter.on(DETAILREADY, handleReady) eventCenter.on(DETAILTOLIST, handleCommand) })
useDidHide(() => { eventCenter.off(DETAILREADY) eventCenter.off(DETAILTOLIST) })
|
原因:每次都进详情页,列表页只被 hide、不会 unload,useUnload 里的 off 根本没机会执行;而 on 在每点一次条目时就执行一次,监听器数量随点击次数线性增长——进两次详情页后点「下一首」,一次会跳两首。
详情页也有同源问题:把 eventCenter.on 放进依赖 [acceptData] 的 useEffect 里,每换一首歌就重新注册一遍,旧的从没被 off,最终多个 onEnded 同时触发、一次结束连跳好几首。**注册类 effect 的依赖数组必须是 []**,换歌只留给 context.src。
4.3 'stop' 分支里调 pause(),onStop 永远不触发
1 2 3 4 5 6 7 8 9 10 11 12
| } else if (type === 'stop' && isplay) { context.pause() setIsPlay(false) }
context.onStop(() => { context.destroy() context.offCanplay() context.offPause() context.offPlay() })
|
1 2 3 4 5 6 7 8
| case 'pause': context.pause() setIsPlay(false) break
context.stop()
|
原因:pause() 与 stop() 是两个 API、两条事件链。按钮传给 handAudio 的 'stop' 实际执行的是 pause(),所以 onStop 从头到尾一次都不会触发——里面那串 destroy + off 是死代码;即便真的触发了,destroy() 会连实例一起销毁,之后无法再播放。清理统一放 useUnload,onStop 只保留「停止后重置 UI」这类逻辑。
同时把参数类型收窄成联合字面量 Action,写成 'stop' 这类不在枚举里的字符串会在编译期直接报错,而不是悄悄落进 else。
4.4 currentTime -= 15 没有下限,可能变成负数
1 2 3
| context.currentTime -= 15 context.currentTime += 15
|
1 2 3
| context.currentTime = Math.max(0, context.currentTime - 15) context.currentTime = Math.min(context.duration || Infinity, context.currentTime + 15)
|
原因:在 10 秒处点快退,currentTime 被赋成 -5。负数不是合法的播放位置,不同平台表现不一致——有的静默忽略(表现为「点了没反应」),有的会抛错并打断当前播放。快进同理,越过 duration 会被夹到末尾却没有触发预期行为。赋值前夹取一次,两端都安全。
4.5 时长换算里 hour 除以 24 * 60
1 2 3 4
| const min = parseInt(`${duration / 60}`) const sec = parseInt(`${duration % 60}`) const hour = parseInt(`${duration / (24 * 60)}`)
|
1 2 3 4 5
| const total = Math.floor(seconds || 0) const h = Math.floor(total / 3600) const m = Math.floor((total % 3600) / 60) const s = total % 60
|
原因:一小时是 3600 秒,24 * 60 = 1440 是「一天的分钟数」,单位完全对不上。按原写法 hour 恒为 0,min 也不取余,超过 60 分钟会变成 01:75:00 这种非法时间。因为练习音频都不超过一小时,这个问题一直没暴露。抽成 formatDuration 后,三处调用(onCanplay、onTimeUpdate、快进快退后的显示)共用一套换算,也不会再各写一遍。
4.6 顺带记录
- **
useState(createInnerAudioContext())**:括号在渲染时执行,每次重渲染都新建实例。应写成 useState(() => createInnerAudioContext())。
context.src 写在渲染体外层:每次渲染都赋一次值,属于「副作用写在渲染里」。放进依赖 acceptData 的 useEffect 更可控。
AtTabs 的 height="800px" 是硬编码:配合 tabDirection="vertical" 使用,小屏可能滚动异常,更稳的是按屏幕高度算。
- 第二组数据格式不一致:源码里「标签页2」的
subList 是字符串数组('w'、'e'、'r'、't'),与其它组的 { id, voiceUrl } 不一致,渲染 {item.id} 时是空白。属于遗留数据,正式项目应统一类型。
- 倍速未接入:源码留了注释,
context.playbackRate 可直接用,是明确的待办。
小结
- 跨页通信靠一套常量 + 两个方向的事件:列表推「播哪条」,详情发
prev / next,数据只存在列表页一份。方案很轻,代价是事件名必须集中管理。
- 发布订阅没有缓冲区:
navigateTo 的 success 早于详情页 useEffect,首屏数据要用「详情页就绪 → 再推数据」的握手,不能靠时序巧合。
- **清理时机要分清
unload 与 hide**:列表页被压在栈里不会卸载,useUnload 清不掉它;useDidShow 注册、useDidHide 解除才是成对的写法。
InnerAudioContext 是事件驱动的:duration / currentTime 都得先读一次才有效,pause 与 stop 是两条事件链,currentTime 可直接赋值做 seek 但要夹取范围,退出页面必须 destroy()。
- 时间换算只留一处:一小时 3600 秒,
formatDuration 收口比在每个回调里各算一遍 hour / min / sec 可靠得多。