AudioStreamDemoRunner.js
7.29 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
* @Description: 首页录音 + WebSocket 边录边传 Demo(NativeWsClient)
*/
import AudioStreamService from './AudioStreamService.js'
import { demoLog } from './demoLog.js'
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import permision from '@/js_sdk/wa-permission/permission.js'
const DEMO_RECORD_MS = 5000
const PCM_START_TIMEOUT_MS = 8000
export default class AudioStreamDemoRunner {
constructor(hooks = {}) {
this._onLog = hooks.onLog || (() => {})
this._onStatus = hooks.onStatus || (() => {})
this._frames = []
this._chunkHandler = null
this._timer = null
this._running = false
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
}
get isRunning() {
return this._running
}
async start() {
// #ifndef APP-PLUS
this._log('warn', '仅 App 端支持')
return false
// #endif
// #ifdef APP-PLUS
if (this._running) {
this._log('warn', 'Demo 进行中')
return false
}
if (plus.os.name !== 'Android') {
this._log('warn', '当前 Demo 仅支持 Android PCM')
return false
}
const permitted = await this._ensureRecordPermission()
if (!permitted) {
this._log('error', '无录音权限')
return false
}
this._running = true
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
this._setStatus('connecting')
this._ws = NativeWsClient.getInstance()
this._prevOnMessage = this._ws.onMessage
this._ws.onMessage = (data) => {
this._log('info', `[WS] 收到 <= ${JSON.stringify(data || {}).slice(0, 240)}`)
this._prevOnMessage && this._prevOnMessage(data)
}
if (!this._ws.isConnected) {
this._log('info', '连接原生 WebSocket(uni.connectSocket)…')
try {
await this._ws.connect()
this._ownsWs = true
} catch (e) {
this._log('error', `WebSocket 连接失败: ${e.message || e}`)
this._cleanup(false)
return false
}
} else {
this._log('info', '复用已有 NativeWs 连接')
}
const stream = AudioStreamService.getInstance()
if (stream.isRunning) {
this._log('warn', 'PCM 采集中(可能接待录音占用麦克风),先停止再试')
stream.stop()
}
this._chunkHandler = (frame) => this._onPcmChunk(frame)
stream.onChunk(this._chunkHandler)
let started = false
try {
started = await Promise.race([
stream.start({ debugLog: true }),
new Promise((_, reject) => {
setTimeout(() => reject(new Error('PCM 启动超时,检查 gl-pcm-capture 插件与麦克风占用')), PCM_START_TIMEOUT_MS)
})
])
} catch (e) {
this._log('error', e.message || String(e))
started = false
}
if (!started) {
this._log('error', 'PCM 采集启动失败(插件未生效或麦克风被占用)')
this._cleanup(false)
return false
}
this._setStatus('recording')
this._log('info', `PCM 已启动,边录边传 ${DEMO_RECORD_MS / 1000}s 后结束`)
this._timer = setTimeout(() => {
this.stopAndUpload()
}, DEMO_RECORD_MS)
return true
// #endif
}
_onPcmChunk(frame) {
this._frames.push({
seq: frame.seq,
base64: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
})
if (frame.seq % 8 === 0) {
this._log('info', `采集中 帧#${frame.seq} ${frame.byteLength}B,已缓存 ${this._frames.length} 帧,已发送 ${this._sentCount} 帧`)
}
const ws = this._ws
if (!ws?.isConnected) return
this._sendChain = this._sendChain
.then(() => this._sendPcmFrame(frame))
.catch((e) => {
this._log('warn', `发送帧#${frame.seq} 失败: ${e.message || e}`)
})
}
async _sendPcmFrame(frame) {
const ws = this._ws
if (!ws?.isConnected) return
if (!this._streamStarted) {
const ok = await ws.send({
command: 'audioStreamStart',
data: {
sampleRate: 16000,
channels: 1,
bitDepth: 16,
format: 'pcm',
demo: true
}
})
if (!ok) {
throw new Error('audioStreamStart 发送失败')
}
this._streamStarted = true
this._log('info', '已发送 audioStreamStart,开始上传 PCM 帧')
}
const ok = await ws.send({
command: 'audioStream',
data: {
seq: frame.seq,
chunk: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
}
})
if (!ok) {
throw new Error(`audioStream seq=${frame.seq} 发送失败`)
}
this._sentCount++
if (this._sentCount % 10 === 0) {
this._log('info', `实时上传 ${this._sentCount} 帧`)
}
}
async stopAndUpload() {
if (!this._running) return
clearTimeout(this._timer)
this._timer = null
this._setStatus('uploading')
this._log('info', '停止录音…')
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
await this._sendChain.catch(() => {})
const total = this._frames.length
const bytes = this._frames.reduce((sum, f) => sum + (f.byteLength || 0), 0)
this._log('info', `录音结束:采集 ${total} 帧 / 已发送 ${this._sentCount} 帧,约 ${(bytes / 1024).toFixed(1)} KB`)
const ws = this._ws
if (ws?.isConnected && this._streamStarted) {
try {
await ws.send({
command: 'audioStreamEnd',
data: { total, sent: this._sentCount, bytes }
})
this._log('info', `已发送 audioStreamEnd sent=${this._sentCount}`)
} catch (e) {
this._log('error', `audioStreamEnd 失败: ${e.message || e}`)
}
} else if (total === 0) {
this._log('warn', '未采集到 PCM 数据,未向服务端发送音频')
} else if (!this._streamStarted) {
this._log('warn', '未发送 audioStreamStart,跳过 audioStreamEnd')
}
this._cleanup(true)
}
cancel() {
clearTimeout(this._timer)
this._timer = null
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
this._cleanup(false)
this._log('warn', 'Demo 已取消')
}
async _ensureRecordPermission() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
const code = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
return code === 1
}
// #endif
return true
}
_cleanup(done) {
this._running = false
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
if (this._ws) {
this._ws.onMessage = this._prevOnMessage
}
if (this._ownsWs && this._ws) {
this._ws.close().catch(() => {})
NativeWsClient.resetInstance()
}
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._setStatus(done ? 'done' : 'idle')
}
_log(level, msg) {
const entry = demoLog(level, msg)
this._onLog(entry)
}
_setStatus(status) {
this._onStatus(status)
}
}