AudioStreamService.js
4.21 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
/*
* @Description: PCM 实时流服务(Android UTS 插件封装)
* 用法:
* const stream = AudioStreamService.getInstance()
* stream.onChunk((frame) => { ... })
* stream.start() / stream.stop()
*/
import { DEFAULT_FRAME_SIZE, DEFAULT_SAMPLE_RATE } from './constants.js'
import { normalizePcmFrame } from './pcmUtils.js'
// #ifdef APP-PLUS
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
// #endif
class AudioStreamService {
static _instance = null
constructor() {
this._listeners = new Set()
this._running = false
this._frameHandler = null
this._logEveryN = 50
this._frameCount = 0
this._lastError = ''
}
get lastError() {
return this._lastError
}
static getInstance() {
if (!AudioStreamService._instance) {
AudioStreamService._instance = new AudioStreamService()
}
return AudioStreamService._instance
}
/**
* 订阅 PCM 帧
* @param {(frame: object) => void} callback frame 含 base64、buffer(ArrayBuffer)、seq 等
* @returns {() => void} 取消订阅
*/
onChunk(callback) {
if (typeof callback !== 'function') {
return () => {}
}
this._listeners.add(callback)
return () => this._listeners.delete(callback)
}
offChunk(callback) {
this._listeners.delete(callback)
}
get isRunning() {
return this._running
}
/**
* @param {object} [options]
* @param {number} [options.sampleRate]
* @param {number} [options.frameSize]
* @param {boolean} [options.debugLog] 是否打印采样日志
*/
start(options = {}) {
// #ifndef APP-PLUS
uni.$logger?.local?.warn('[AudioStream] 仅 App 端支持')
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
if (plus.os.name !== 'Android') {
uni.$logger?.local?.warn('[AudioStream] 当前仅实现 Android PCM 采集')
return Promise.resolve(false)
}
if (typeof startPcmCapture !== 'function') {
this._lastError = 'gl-pcm-capture 未加载(缺少 utssdk/index.uts 或未打自定义基座)'
uni.$logger?.local?.error(`[AudioStream] ${this._lastError}`)
return Promise.resolve(false)
}
if (this._running) {
return Promise.resolve(true)
}
this._lastError = ''
const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
const frameSize = options.frameSize || DEFAULT_FRAME_SIZE
const debugLog = options.debugLog !== false
this._frameHandler = (frame) => {
const normalized = normalizePcmFrame(frame)
this._frameCount++
if (debugLog && this._frameCount % this._logEveryN === 1) {
uni.$logger?.local?.info(
`[AudioStream] frame#${normalized.seq} bytes=${normalized.byteLength} ts=${normalized.timestamp}`
)
}
this._listeners.forEach((cb) => {
try {
cb(normalized)
} catch (e) {
uni.$logger?.local?.error(`[AudioStream] listener error: ${e.message}`)
}
})
}
onPcmFrame(this._frameHandler)
return new Promise((resolve) => {
try {
startPcmCapture({
sampleRate,
frameSize,
success: () => {
this._running = true
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已启动')
resolve(true)
},
fail: (err) => {
offPcmFrame()
this._frameHandler = null
this._lastError = err?.errMsg || JSON.stringify(err) || 'startPcmCapture fail'
uni.$logger?.local?.error(`[AudioStream] 启动失败: ${this._lastError}`)
resolve(false)
}
})
} catch (e) {
offPcmFrame()
this._frameHandler = null
this._lastError = e?.message || String(e)
uni.$logger?.local?.error(`[AudioStream] 启动异常: ${this._lastError}`)
resolve(false)
}
})
// #endif
}
stop() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
stopPcmCapture()
offPcmFrame()
}
// #endif
this._running = false
this._frameHandler = null
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已停止')
}
}
export default AudioStreamService