AudioFramePool.js
8.09 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
276
277
278
279
280
281
282
/*
* 音频帧缓冲池
* 维护最近 N 秒的 PCM 音频帧,支持截取上传
*/
const DEFAULT_SAMPLE_RATE = 16000
const DEFAULT_CHANNELS = 1
const DEFAULT_BITS_PER_SAMPLE = 16
const WAV_HEADER_SIZE = 44
// 格式配置:format -> { contentType, needHeader }
const FORMAT_CONFIG = {
wav: { contentType: 'audio/wav', needHeader: true },
pcm: { contentType: 'application/octet-stream', needHeader: false }
}
export default class AudioFramePool {
/**
* @param {Object} options
* @param {number} options.maxSeconds - 最大保留秒数,默认 60
* @param {number} options.sampleRate - 采样率,默认 16000
* @param {number} options.channels - 声道数,默认 1
* @param {number} options.bitsPerSample - 位深,默认 16
*/
constructor(options = {}) {
this.sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
this.channels = options.channels || DEFAULT_CHANNELS
this.bitsPerSample = options.bitsPerSample || DEFAULT_BITS_PER_SAMPLE
this.maxSeconds = options.maxSeconds || 60
// 每秒字节数: sampleRate * channels * (bitsPerSample / 8)
this.bytesPerSecond = this.sampleRate * this.channels * (this.bitsPerSample / 8)
this.maxBytes = this.bytesPerSecond * this.maxSeconds
// 帧队列: Uint8Array[]
this.frames = []
this.totalBytes = 0
}
/**
* 推入一帧音频数据
* @param {string} base64 - base64 编码的 PCM 数据
*/
push(base64) {
if (!base64 || typeof base64 !== 'string') return
let buffer
try {
// uni-app 内置 API,全平台可用
buffer = uni.base64ToArrayBuffer(base64)
} catch (e) {
uni.$logger?.local?.error(`AudioFramePool: base64解码失败 ${e.message}`)
return
}
const bytes = new Uint8Array(buffer)
this.frames.push(bytes)
this.totalBytes += bytes.byteLength
// 淘汰旧帧
this._evict()
}
/**
* 淘汰超出上限的旧帧
*/
_evict() {
while (this.totalBytes > this.maxBytes && this.frames.length > 0) {
const removed = this.frames.shift()
this.totalBytes -= removed.byteLength
}
}
/**
* 获取当前缓冲池中的音频时长(秒)
*/
getDuration() {
return this.totalBytes / this.bytesPerSecond
}
/**
* 截取当前缓冲池中的音频
* @param {number} [seconds] - 截取最近多少秒,不传则截取全部
* @param {string} [format='pcm'] - 输出格式:'pcm'(纯 PCM)
* @returns {ArrayBuffer|null} ArrayBuffer
*/
capture(seconds, format = 'pcm') {
if (this.frames.length === 0) {
uni.$logger?.local?.warn('AudioFramePool: 缓冲池为空')
return null
}
let targetBytes = this.totalBytes
if (seconds && seconds > 0) {
targetBytes = Math.min(seconds * this.bytesPerSecond, this.totalBytes)
}
// 从末尾向前取帧
const selected = []
let selectedBytes = 0
for (let i = this.frames.length - 1; i >= 0; i--) {
selected.unshift(this.frames[i])
selectedBytes += this.frames[i].byteLength
if (selectedBytes >= targetBytes) break
}
// 拼接所有选中帧
const pcmData = new Uint8Array(selectedBytes)
let offset = 0
for (const frame of selected) {
pcmData.set(frame, offset)
offset += frame.byteLength
}
// 如果取出的字节超过目标,裁剪头部多余部分
const trimmed = selectedBytes > targetBytes
? pcmData.slice(selectedBytes - targetBytes)
: pcmData
// 根据格式决定是否添加 WAV 头
return FORMAT_CONFIG[format].needHeader ? this._addWavHeader(trimmed) : trimmed.buffer
}
/**
* 截取并上传
* @param {Object} options
* @param {string} options.url - 上传接口地址
* @param {number} [options.seconds] - 截取最近多少秒
* @param {string} [options.format='pcm'] - 音频格式:'wav' 或 'pcm'
* @param {Object} [options.header] - 请求头(如 Authorization)
* @returns {Promise<Object>}
*/
async upload(options) {
const { url, seconds, format = 'pcm', header = {} } = options
// if (!url) {
// throw new Error('上传 URL 不能为空')
// }
const audioBuffer = this.capture(seconds, format)
if (!audioBuffer) {
throw new Error('缓冲池为空,无数据可上传')
}
// const pcmSize = FORMAT_CONFIG[format].needHeader ? (audioBuffer.byteLength - WAV_HEADER_SIZE) : audioBuffer.byteLength
// const actualDuration = Math.round(pcmSize / this.bytesPerSecond * 1000) / 1000
// const fileName = `clip_${Date.now()}_${actualDuration}s.${format}`
const contentType = FORMAT_CONFIG[format].contentType
// #ifdef H5
return this._uploadH5(url, audioBuffer, contentType, header)
// #endif
// #ifdef APP-PLUS
return this._uploadApp(url, audioBuffer, contentType, header)
// #endif
}
/**
* H5 平台上传
*/
_uploadH5(url, arrayBuffer, contentType, header = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
xhr.setRequestHeader('Content-Type', contentType)
// 应用额外请求头
Object.entries(header).forEach(([key, value]) => {
xhr.setRequestHeader(key, value)
})
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else {
reject(new Error(`上传失败: ${xhr.status}`))
}
}
xhr.onerror = () => reject(new Error('网络错误'))
xhr.send(arrayBuffer)
})
}
/**
* App 平台上传:直接 ArrayBuffer 通过 uni.request 发送
*/
async _uploadApp(url, arrayBuffer, contentType, header = {}) {
return new Promise((resolve, reject) => {
uni.request({
url,
method: 'POST',
header: {
...header,
'Content-Type': contentType
},
data: arrayBuffer,
success: (res) => resolve(res.data),
fail: (err) => reject(new Error(err.errMsg))
})
})
}
/**
* 用原生 API 写二进制文件(Android/iOS 通用)
*/
async _writeBinaryFile(absPath, arrayBuffer) {
const base64 = uni.arrayBufferToBase64(arrayBuffer)
// #ifdef APP-ANDROID
const Base64 = plus.android.importClass('android.util.Base64')
const javaBytes = Base64.decode(base64, 0)
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
const fos = new FileOutputStream(absPath)
fos.write(javaBytes)
fos.close()
// #endif
// #ifdef APP-IOS
const NSData = plus.ios.importClass('NSData')
const data = NSData.alloc().initWithBase64EncodedStringOptions(base64, 0)
data.writeToFileAtomically(absPath, true)
plus.ios.deleteObject(data)
// #endif
}
/**
* 为 PCM 数据添加 WAV 文件头
* @param {Uint8Array} pcmData - 原始 PCM 数据
* @returns {ArrayBuffer}
*/
_addWavHeader(pcmData) {
const dataSize = pcmData.byteLength
const buffer = new ArrayBuffer(WAV_HEADER_SIZE + dataSize)
const view = new DataView(buffer)
// RIFF header
this._writeString(view, 0, 'RIFF')
view.setUint32(4, 36 + dataSize, true)
this._writeString(view, 8, 'WAVE')
// fmt chunk
this._writeString(view, 12, 'fmt ')
view.setUint32(16, 16, true)
view.setUint16(20, 1, true) // PCM format
view.setUint16(22, this.channels, true)
view.setUint32(24, this.sampleRate, true)
view.setUint32(28, this.bytesPerSecond, true)
view.setUint16(32, this.channels * (this.bitsPerSample / 8), true)
view.setUint16(34, this.bitsPerSample, true)
// data chunk
this._writeString(view, 36, 'data')
view.setUint32(40, dataSize, true)
// 拼接 PCM 数据
const wav = new Uint8Array(buffer)
wav.set(pcmData, WAV_HEADER_SIZE)
return buffer
}
_writeString(view, offset, str) {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i))
}
}
/**
* 清空缓冲池
*/
reset() {
this.frames = []
this.totalBytes = 0
}
/**
* 获取缓冲池状态
*/
getStatus() {
return {
frameCount: this.frames.length,
totalBytes: this.totalBytes,
duration: this.getDuration().toFixed(2) + 's',
maxSeconds: this.maxSeconds
}
}
}