react-native-pcm-player-lite 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -37
- package/android/build.gradle +3 -1
- package/android/src/main/AndroidManifest.xml +1 -1
- package/android/src/main/java/com/pcmplayer/PcmPlayback.kt +283 -0
- package/android/src/main/java/com/pcmplayer/PcmPlayerModule.kt +168 -51
- package/android/src/test/java/com/pcmplayer/PcmPlaybackTest.kt +292 -0
- package/ios/PcmAudioRenderer.swift +85 -0
- package/ios/PcmPlayback.swift +206 -0
- package/ios/PcmPlayer.swift +75 -59
- package/ios/PcmPlayerModule.m +8 -2
- package/package.json +8 -1
- package/react-native-pcm-player-lite.podspec +1 -1
- package/src/index.d.ts +44 -9
- package/src/index.js +102 -34
package/README.md
CHANGED
|
@@ -1,60 +1,66 @@
|
|
|
1
1
|
# react-native-pcm-player-lite
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
Works great for AI voice assistants that stream raw PCM over sockets.
|
|
3
|
+
Play streaming signed 16-bit little-endian mono PCM in a React Native app. Provide raw samples at a fixed sample rate and send audio as it arrives.
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
- iOS: `AVAudioEngine` + `AVAudioPlayerNode` (converts Int16 -> Float32)
|
|
5
|
+
## Quick start
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
1. Install the published package.
|
|
10
8
|
|
|
11
|
-
|
|
9
|
+
```sh
|
|
10
|
+
npm install react-native-pcm-player-lite
|
|
11
|
+
```
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
# or
|
|
16
|
-
yarn add react-native-pcm-player-lite
|
|
17
|
-
```
|
|
13
|
+
2. Rebuild the native app. For iOS, run `pod install` in your app's `ios` directory first. For Expo, use a [development build](docs/content/expo.md).
|
|
14
|
+
3. Start playback before forwarding audio chunks. Call `stopPlayback()` after playback finishes or when the user cancels.
|
|
18
15
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
cd ios && pod install && cd ..
|
|
22
|
-
```
|
|
16
|
+
```ts
|
|
17
|
+
import PCM from 'react-native-pcm-player-lite';
|
|
23
18
|
|
|
24
|
-
|
|
19
|
+
async function startPlayback() {
|
|
20
|
+
await PCM.start(24000);
|
|
21
|
+
}
|
|
25
22
|
|
|
26
|
-
|
|
23
|
+
function onAudioChunk(chunkBase64: string) {
|
|
24
|
+
PCM.enqueueBase64(chunkBase64);
|
|
25
|
+
}
|
|
27
26
|
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
async function stopPlayback() {
|
|
28
|
+
await PCM.stop();
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Binary audio in 0.2.0
|
|
30
33
|
|
|
31
|
-
|
|
34
|
+
After starting the player, forward each chunk of mono PCM16 bytes. When the user interrupts, stop forwarding the old stream before clearing its queued audio.
|
|
32
35
|
|
|
33
|
-
|
|
34
|
-
|
|
36
|
+
```ts
|
|
37
|
+
function onBinaryChunk(bytes: Uint8Array) {
|
|
38
|
+
PCM.enqueue(bytes);
|
|
39
|
+
}
|
|
35
40
|
|
|
36
|
-
|
|
37
|
-
await PCM.
|
|
41
|
+
async function discardQueuedAudio() {
|
|
42
|
+
await PCM.flush();
|
|
43
|
+
}
|
|
38
44
|
```
|
|
39
45
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
- At 24 kHz mono, 40 ms = 960 samples = 1920 bytes.
|
|
46
|
+
## Documentation
|
|
47
|
+
|
|
48
|
+
Read the [documentation overview](docs/content/index.md), [first-playback tutorial](docs/content/first-playback.md), or [API reference](docs/content/api.md).
|
|
44
49
|
|
|
45
|
-
|
|
50
|
+
To run the Docusaurus site locally with Node.js 20 or later:
|
|
46
51
|
|
|
47
|
-
|
|
52
|
+
```sh
|
|
53
|
+
cd docs
|
|
54
|
+
npm ci
|
|
55
|
+
npm start
|
|
56
|
+
```
|
|
48
57
|
|
|
49
|
-
|
|
50
|
-
- `enqueueBase64(base64Chunk: string): void` – Push raw PCM data (base64 string).
|
|
51
|
-
- `stop(): Promise<void>` – Stop and release resources.
|
|
58
|
+
Run `npm run build` from `docs/` to build the static site into `docs/build/`.
|
|
52
59
|
|
|
53
|
-
##
|
|
60
|
+
## Expo demo
|
|
54
61
|
|
|
55
|
-
|
|
56
|
-
- **Stutter on Android?** Increase queue size or send slightly larger chunks (e.g., 20–40 ms).
|
|
57
|
-
- **iOS quiet/muted?** Check the device's silent switch and ensure your app's audio session allows playback.
|
|
62
|
+
The [PCM Player Demo](examples/pcm-player-demo/README.md) plays a generated tone offline and displays queue depth and playback events.
|
|
58
63
|
|
|
59
64
|
## License
|
|
65
|
+
|
|
60
66
|
MIT
|
package/android/build.gradle
CHANGED
|
@@ -15,6 +15,7 @@ plugins {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
android {
|
|
18
|
+
namespace "com.pcmplayer"
|
|
18
19
|
compileSdkVersion 34
|
|
19
20
|
|
|
20
21
|
defaultConfig {
|
|
@@ -39,6 +40,7 @@ repositories {
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
dependencies {
|
|
43
|
+
testImplementation "junit:junit:4.13.2"
|
|
42
44
|
implementation "com.facebook.react:react-android"
|
|
43
45
|
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.8.22"
|
|
44
|
-
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
package com.pcmplayer
|
|
2
|
+
|
|
3
|
+
import java.nio.ByteBuffer
|
|
4
|
+
import java.util.ArrayDeque
|
|
5
|
+
import kotlin.concurrent.thread
|
|
6
|
+
|
|
7
|
+
internal interface PcmOutput {
|
|
8
|
+
fun pause()
|
|
9
|
+
fun play()
|
|
10
|
+
fun write(buffer: ByteBuffer): Int
|
|
11
|
+
fun finishPriming(): Int = 0
|
|
12
|
+
fun playbackHead(): Int
|
|
13
|
+
fun underrunCount(): Int?
|
|
14
|
+
fun flush()
|
|
15
|
+
fun release()
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
internal data class PcmStatus(val state: String, val queueDepth: Int)
|
|
19
|
+
|
|
20
|
+
internal class PcmPlayback(
|
|
21
|
+
private val createOutput: (Int) -> PcmOutput,
|
|
22
|
+
private val decode: (String) -> ByteArray,
|
|
23
|
+
private val emit: (String, String?) -> Unit
|
|
24
|
+
) {
|
|
25
|
+
private class Chunk(val buffer: ByteBuffer) {
|
|
26
|
+
var endFrame: Long? = null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
private class Session(val output: PcmOutput, var preserve: Boolean) {
|
|
30
|
+
var interrupted = false
|
|
31
|
+
val pending = ArrayDeque<Chunk>()
|
|
32
|
+
val unwritten = ArrayDeque<Chunk>()
|
|
33
|
+
lateinit var worker: Thread
|
|
34
|
+
var submittedFrames = 0L
|
|
35
|
+
var renderedFrames = 0L
|
|
36
|
+
var lastHead = 0L
|
|
37
|
+
var underruns: Int? = null
|
|
38
|
+
var reportedUnderrun = false
|
|
39
|
+
var burstStartFrame = 0L
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private val lock = Object()
|
|
43
|
+
private var session: Session? = null
|
|
44
|
+
private var invalidated = false
|
|
45
|
+
|
|
46
|
+
@Synchronized
|
|
47
|
+
fun start(rate: Double, preserve: Boolean = true) {
|
|
48
|
+
require(rate in 8000.0..96000.0 && rate == rate.toInt().toDouble()) {
|
|
49
|
+
"Sample rate must be an integer between 8000 and 96000"
|
|
50
|
+
}
|
|
51
|
+
synchronized(lock) {
|
|
52
|
+
check(!invalidated) { "Playback module has been invalidated" }
|
|
53
|
+
session?.let { it.preserve = preserve; return }
|
|
54
|
+
val current = Session(createOutput(rate.toInt()), preserve)
|
|
55
|
+
try {
|
|
56
|
+
current.output.play()
|
|
57
|
+
current.underruns = current.output.underrunCount()
|
|
58
|
+
session = current
|
|
59
|
+
current.worker = thread(name = "PcmPlayer", isDaemon = true) { runWorker(current) }
|
|
60
|
+
emit("started", null)
|
|
61
|
+
} catch (failure: Exception) {
|
|
62
|
+
close(current, failure)
|
|
63
|
+
throw failure
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fun enqueueBase64(encoded: String) {
|
|
69
|
+
val bytes = try {
|
|
70
|
+
val normalized = encoded.filterNot { it == ' ' || it == '\n' || it == '\r' || it == '\t' }
|
|
71
|
+
if (normalized.isEmpty()) return
|
|
72
|
+
require(normalized.matches(BASE64) && normalized.length % 4 != 1 &&
|
|
73
|
+
('=' !in normalized || normalized.length % 4 == 0))
|
|
74
|
+
decode(normalized).also { require(it.size % 2 == 0) }
|
|
75
|
+
} catch (_: IllegalArgumentException) {
|
|
76
|
+
synchronized(lock) { emit("error", "Expected base64-encoded 16-bit PCM") }
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
if (bytes.isEmpty()) return
|
|
80
|
+
synchronized(lock) {
|
|
81
|
+
val current = session
|
|
82
|
+
if (current == null) {
|
|
83
|
+
emit("error", "Playback has not started")
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
if (current.interrupted && !current.preserve) return
|
|
87
|
+
if (current.pending.size == MAX_PENDING) {
|
|
88
|
+
emit("error", "Playback queue is full")
|
|
89
|
+
return
|
|
90
|
+
}
|
|
91
|
+
if (current.pending.isEmpty()) {
|
|
92
|
+
current.burstStartFrame = current.submittedFrames
|
|
93
|
+
}
|
|
94
|
+
val chunk = Chunk(ByteBuffer.wrap(bytes))
|
|
95
|
+
current.pending.addLast(chunk)
|
|
96
|
+
current.unwritten.addLast(chunk)
|
|
97
|
+
lock.notifyAll()
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
fun status(): PcmStatus = synchronized(lock) {
|
|
102
|
+
val depth = session?.pending?.size
|
|
103
|
+
PcmStatus(if (session?.interrupted == true) "interrupted" else when (depth) {
|
|
104
|
+
null -> "stopped"
|
|
105
|
+
0 -> "idle"
|
|
106
|
+
else -> "playing"
|
|
107
|
+
}, depth ?: 0)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
@Synchronized
|
|
111
|
+
fun stop() {
|
|
112
|
+
val current: Session
|
|
113
|
+
val failure: Exception?
|
|
114
|
+
synchronized(lock) {
|
|
115
|
+
current = session ?: return
|
|
116
|
+
failure = close(current)
|
|
117
|
+
}
|
|
118
|
+
joinWorker(current.worker)
|
|
119
|
+
if (failure != null) throw failure
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
@Synchronized
|
|
123
|
+
fun invalidate() {
|
|
124
|
+
synchronized(lock) { invalidated = true }
|
|
125
|
+
stop()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@Synchronized
|
|
129
|
+
fun flush() {
|
|
130
|
+
var failedSession: Session? = null
|
|
131
|
+
var failure: Exception? = null
|
|
132
|
+
synchronized(lock) {
|
|
133
|
+
val current = session ?: return
|
|
134
|
+
try {
|
|
135
|
+
clearQueue(current)
|
|
136
|
+
} catch (error: Exception) {
|
|
137
|
+
failedSession = current
|
|
138
|
+
failure = close(current, error)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
failedSession?.let { joinWorker(it.worker) }
|
|
142
|
+
failure?.let { throw it }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private fun clearQueue(current: Session) {
|
|
146
|
+
current.output.flush()
|
|
147
|
+
if (!current.interrupted) current.output.play()
|
|
148
|
+
current.pending.clear()
|
|
149
|
+
current.unwritten.clear()
|
|
150
|
+
current.submittedFrames = 0
|
|
151
|
+
current.renderedFrames = 0
|
|
152
|
+
current.lastHead = 0
|
|
153
|
+
current.underruns = current.output.underrunCount()
|
|
154
|
+
current.reportedUnderrun = false
|
|
155
|
+
current.burstStartFrame = 0
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
@Synchronized
|
|
159
|
+
fun focusChanged(output: PcmOutput, gained: Boolean, permanent: Boolean) {
|
|
160
|
+
val current = synchronized(lock) { session } ?: return
|
|
161
|
+
if (current.output !== output) return
|
|
162
|
+
if (permanent) {
|
|
163
|
+
stop()
|
|
164
|
+
emit("error", "Audio focus lost. Start playback again to continue.")
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
synchronized(lock) {
|
|
168
|
+
if (session !== current || current.interrupted == !gained) return
|
|
169
|
+
try {
|
|
170
|
+
current.interrupted = !gained
|
|
171
|
+
if (gained) {
|
|
172
|
+
current.output.play()
|
|
173
|
+
lock.notifyAll()
|
|
174
|
+
} else {
|
|
175
|
+
current.output.pause()
|
|
176
|
+
if (!current.preserve) clearQueue(current)
|
|
177
|
+
}
|
|
178
|
+
emit(if (gained) "started" else "interrupted", null)
|
|
179
|
+
} catch (failure: Exception) {
|
|
180
|
+
if (session === current) close(current, failure)
|
|
181
|
+
emit("error", failure.message)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private fun runWorker(current: Session) {
|
|
187
|
+
while (true) {
|
|
188
|
+
synchronized(lock) {
|
|
189
|
+
if (session !== current) return
|
|
190
|
+
try {
|
|
191
|
+
if (current.interrupted || current.pending.isEmpty()) {
|
|
192
|
+
lock.wait()
|
|
193
|
+
} else {
|
|
194
|
+
updateProgress(current)
|
|
195
|
+
val wrote = write(current)
|
|
196
|
+
if (!wrote && current.pending.isNotEmpty()) lock.wait(POLL_MS)
|
|
197
|
+
}
|
|
198
|
+
} catch (failure: Exception) {
|
|
199
|
+
close(current, failure)
|
|
200
|
+
emit("error", failure.message ?: "Audio playback failed")
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private fun updateProgress(current: Session) {
|
|
207
|
+
val head = current.output.playbackHead().toLong() and HEAD_MASK
|
|
208
|
+
current.renderedFrames += (head - current.lastHead) and HEAD_MASK
|
|
209
|
+
current.lastHead = head
|
|
210
|
+
|
|
211
|
+
val underruns = current.output.underrunCount()
|
|
212
|
+
val previousUnderruns = current.underruns
|
|
213
|
+
if (!current.reportedUnderrun && current.submittedFrames > current.burstStartFrame &&
|
|
214
|
+
underruns != null && previousUnderruns != null && underruns > previousUnderruns
|
|
215
|
+
) {
|
|
216
|
+
current.reportedUnderrun = true
|
|
217
|
+
emit("underrun", null)
|
|
218
|
+
}
|
|
219
|
+
current.underruns = underruns
|
|
220
|
+
|
|
221
|
+
while (true) {
|
|
222
|
+
val endFrame = current.pending.peekFirst()?.endFrame ?: return
|
|
223
|
+
if (endFrame > current.renderedFrames) return
|
|
224
|
+
current.pending.removeFirst()
|
|
225
|
+
if (current.pending.isEmpty()) {
|
|
226
|
+
current.reportedUnderrun = false
|
|
227
|
+
emit("drained", null)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private fun write(current: Session): Boolean {
|
|
233
|
+
val chunk = current.unwritten.peekFirst()
|
|
234
|
+
if (chunk == null) {
|
|
235
|
+
if (current.pending.isEmpty()) return false
|
|
236
|
+
val paddingFrames = current.output.finishPriming()
|
|
237
|
+
current.submittedFrames += paddingFrames
|
|
238
|
+
return paddingFrames > 0
|
|
239
|
+
}
|
|
240
|
+
val remaining = chunk.buffer.remaining()
|
|
241
|
+
val count = current.output.write(chunk.buffer)
|
|
242
|
+
check(count in 0..remaining && count % 2 == 0) { "AudioTrack write failed ($count)" }
|
|
243
|
+
current.submittedFrames += count / 2
|
|
244
|
+
if (!chunk.buffer.hasRemaining()) {
|
|
245
|
+
chunk.endFrame = current.submittedFrames
|
|
246
|
+
current.unwritten.removeFirst()
|
|
247
|
+
}
|
|
248
|
+
return count > 0
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Called with lock held so no write can race with output release.
|
|
252
|
+
private fun close(current: Session, failure: Exception? = null): Exception? {
|
|
253
|
+
session = null
|
|
254
|
+
current.pending.clear()
|
|
255
|
+
current.unwritten.clear()
|
|
256
|
+
lock.notifyAll()
|
|
257
|
+
return try {
|
|
258
|
+
current.output.release()
|
|
259
|
+
failure
|
|
260
|
+
} catch (releaseError: Exception) {
|
|
261
|
+
if (failure == null) releaseError else failure.apply { addSuppressed(releaseError) }
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private fun joinWorker(worker: Thread) {
|
|
266
|
+
var interrupted = false
|
|
267
|
+
while (worker.isAlive) {
|
|
268
|
+
try {
|
|
269
|
+
worker.join()
|
|
270
|
+
} catch (_: InterruptedException) {
|
|
271
|
+
interrupted = true
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (interrupted) Thread.currentThread().interrupt()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
private companion object {
|
|
278
|
+
const val MAX_PENDING = 64
|
|
279
|
+
const val POLL_MS = 5L
|
|
280
|
+
const val HEAD_MASK = 0xffffffffL
|
|
281
|
+
val BASE64 = Regex("[A-Za-z0-9+/]+={0,2}")
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -1,76 +1,193 @@
|
|
|
1
1
|
package com.pcmplayer
|
|
2
2
|
|
|
3
|
-
import
|
|
3
|
+
import android.media.AudioAttributes
|
|
4
|
+
import android.media.AudioFocusRequest
|
|
4
5
|
import android.media.AudioFormat
|
|
5
6
|
import android.media.AudioManager
|
|
6
7
|
import android.media.AudioTrack
|
|
8
|
+
import android.os.Build
|
|
7
9
|
import android.util.Base64
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
+
import com.facebook.react.bridge.Arguments
|
|
11
|
+
import com.facebook.react.bridge.Promise
|
|
12
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
13
|
+
import com.facebook.react.bridge.ReactContextBaseJavaModule
|
|
14
|
+
import com.facebook.react.bridge.ReactMethod
|
|
15
|
+
import com.facebook.react.modules.core.DeviceEventManagerModule
|
|
16
|
+
import java.nio.ByteBuffer
|
|
10
17
|
|
|
11
18
|
class PcmPlayerModule(reactContext: ReactApplicationContext) :
|
|
12
19
|
ReactContextBaseJavaModule(reactContext) {
|
|
13
20
|
|
|
14
|
-
private
|
|
15
|
-
|
|
16
|
-
|
|
21
|
+
private val playback = PcmPlayback(
|
|
22
|
+
createOutput = ::createOutput,
|
|
23
|
+
decode = { Base64.decode(it, Base64.DEFAULT) },
|
|
24
|
+
emit = ::emitEvent
|
|
25
|
+
)
|
|
17
26
|
|
|
18
27
|
override fun getName() = "PcmPlayer"
|
|
19
28
|
|
|
20
29
|
@ReactMethod
|
|
21
|
-
fun start(sampleRate:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
sampleRate,
|
|
26
|
-
AudioFormat.CHANNEL_OUT_MONO,
|
|
27
|
-
AudioFormat.ENCODING_PCM_16BIT
|
|
28
|
-
)
|
|
29
|
-
track = AudioTrack(
|
|
30
|
-
AudioManager.STREAM_MUSIC,
|
|
31
|
-
sampleRate,
|
|
32
|
-
AudioFormat.CHANNEL_OUT_MONO,
|
|
33
|
-
AudioFormat.ENCODING_PCM_16BIT,
|
|
34
|
-
minBuf * 2,
|
|
35
|
-
AudioTrack.MODE_STREAM
|
|
36
|
-
)
|
|
37
|
-
track!!.play()
|
|
38
|
-
playing = true
|
|
39
|
-
thread(isDaemon = true) {
|
|
40
|
-
val t = track!!
|
|
41
|
-
while (playing) {
|
|
42
|
-
val data = queue.take() // blocks
|
|
43
|
-
var off = 0
|
|
44
|
-
while (off < data.size) {
|
|
45
|
-
val wrote = t.write(data, off, data.size - off, AudioTrack.WRITE_BLOCKING)
|
|
46
|
-
if (wrote > 0) off += wrote else break
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
promise.resolve(null)
|
|
51
|
-
} catch (e: Exception) {
|
|
52
|
-
promise.reject("ERR_START", e)
|
|
30
|
+
fun start(sampleRate: Double, policy: String, promise: Promise) =
|
|
31
|
+
resolve(promise, "ERR_START") {
|
|
32
|
+
playback.start(sampleRate, policy == "preserve")
|
|
33
|
+
null
|
|
53
34
|
}
|
|
35
|
+
|
|
36
|
+
@ReactMethod
|
|
37
|
+
fun enqueueBase64(b64: String) = playback.enqueueBase64(b64)
|
|
38
|
+
|
|
39
|
+
@ReactMethod
|
|
40
|
+
fun stop(promise: Promise) = resolve(promise, "ERR_STOP") {
|
|
41
|
+
playback.stop()
|
|
42
|
+
null
|
|
54
43
|
}
|
|
55
44
|
|
|
56
45
|
@ReactMethod
|
|
57
|
-
fun
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
46
|
+
fun flush(promise: Promise) = resolve(promise, "ERR_FLUSH") {
|
|
47
|
+
playback.flush()
|
|
48
|
+
null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@ReactMethod
|
|
52
|
+
fun getStatus(promise: Promise) = resolve(promise, "ERR_STATUS") {
|
|
53
|
+
val status = playback.status()
|
|
54
|
+
Arguments.createMap().apply {
|
|
55
|
+
putString("state", status.state)
|
|
56
|
+
putInt("queueDepth", status.queueDepth)
|
|
57
|
+
}
|
|
62
58
|
}
|
|
63
59
|
|
|
64
60
|
@ReactMethod
|
|
65
|
-
fun
|
|
61
|
+
fun addListener(eventName: String) = Unit
|
|
62
|
+
|
|
63
|
+
@ReactMethod
|
|
64
|
+
fun removeListeners(count: Double) = Unit
|
|
65
|
+
|
|
66
|
+
override fun invalidate() {
|
|
67
|
+
try {
|
|
68
|
+
playback.invalidate()
|
|
69
|
+
} finally {
|
|
70
|
+
super.invalidate()
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private fun emitEvent(type: String, message: String?) {
|
|
75
|
+
val context = reactApplicationContext
|
|
76
|
+
if (!context.hasActiveReactInstance()) return
|
|
77
|
+
val payload = Arguments.createMap().apply {
|
|
78
|
+
putString("type", type)
|
|
79
|
+
if (message != null) putString("message", message)
|
|
80
|
+
}
|
|
81
|
+
context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
|
82
|
+
.emit("PcmPlayerEvent", payload)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private inline fun resolve(promise: Promise, code: String, action: () -> Any?) {
|
|
86
|
+
try {
|
|
87
|
+
promise.resolve(action())
|
|
88
|
+
} catch (failure: Exception) {
|
|
89
|
+
promise.reject(code, failure)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private fun createOutput(rate: Int): PcmOutput {
|
|
94
|
+
val minimum = AudioTrack.getMinBufferSize(
|
|
95
|
+
rate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT
|
|
96
|
+
)
|
|
97
|
+
check(minimum > 0) { "Unsupported AudioTrack format ($minimum)" }
|
|
98
|
+
val track = AudioTrack(
|
|
99
|
+
AudioManager.STREAM_MUSIC,
|
|
100
|
+
rate,
|
|
101
|
+
AudioFormat.CHANNEL_OUT_MONO,
|
|
102
|
+
AudioFormat.ENCODING_PCM_16BIT,
|
|
103
|
+
minimum * 2,
|
|
104
|
+
AudioTrack.MODE_STREAM
|
|
105
|
+
)
|
|
106
|
+
if (track.state != AudioTrack.STATE_INITIALIZED) {
|
|
107
|
+
track.release()
|
|
108
|
+
error("Could not initialize AudioTrack")
|
|
109
|
+
}
|
|
110
|
+
val manager = reactApplicationContext.getSystemService(android.content.Context.AUDIO_SERVICE) as AudioManager
|
|
111
|
+
lateinit var output: AudioTrackOutput
|
|
112
|
+
val listener = AudioManager.OnAudioFocusChangeListener { change ->
|
|
113
|
+
when (change) {
|
|
114
|
+
AudioManager.AUDIOFOCUS_GAIN -> playback.focusChanged(output, true, false)
|
|
115
|
+
AudioManager.AUDIOFOCUS_LOSS -> playback.focusChanged(output, false, true)
|
|
116
|
+
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ->
|
|
117
|
+
playback.focusChanged(output, false, false)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
val granted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
121
|
+
val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
|
122
|
+
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
|
|
123
|
+
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
|
|
124
|
+
.setWillPauseWhenDucked(true)
|
|
125
|
+
.setOnAudioFocusChangeListener(listener)
|
|
126
|
+
.build()
|
|
127
|
+
output = AudioTrackOutput(track, minimum * 2) { manager.abandonAudioFocusRequest(request) }
|
|
128
|
+
manager.requestAudioFocus(request)
|
|
129
|
+
} else {
|
|
130
|
+
output = AudioTrackOutput(track, minimum * 2) { manager.abandonAudioFocus(listener) }
|
|
131
|
+
manager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
|
|
132
|
+
}
|
|
133
|
+
if (granted != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
|
134
|
+
track.release()
|
|
135
|
+
error("Audio focus denied")
|
|
136
|
+
}
|
|
137
|
+
return output
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private class AudioTrackOutput(
|
|
142
|
+
private val track: AudioTrack,
|
|
143
|
+
private val bufferBytes: Int,
|
|
144
|
+
private val abandonFocus: () -> Unit
|
|
145
|
+
) : PcmOutput {
|
|
146
|
+
private var needsPriming = Build.VERSION.SDK_INT < Build.VERSION_CODES.S
|
|
147
|
+
private val silence by lazy { ByteBuffer.allocate(bufferBytes) }
|
|
148
|
+
|
|
149
|
+
override fun pause() = track.pause()
|
|
150
|
+
|
|
151
|
+
override fun play() {
|
|
152
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) track.setStartThresholdInFrames(1)
|
|
153
|
+
track.play()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
override fun write(buffer: ByteBuffer): Int =
|
|
157
|
+
track.write(buffer, buffer.remaining(), AudioTrack.WRITE_NON_BLOCKING)
|
|
158
|
+
|
|
159
|
+
// Older Android versions can wait for a full buffer before rendering the first frame.
|
|
160
|
+
// Pad only the initial short burst, and keep padding outside PCM chunk boundaries.
|
|
161
|
+
override fun finishPriming(): Int {
|
|
162
|
+
if (!needsPriming) return 0
|
|
163
|
+
if (track.playbackHeadPosition != 0) {
|
|
164
|
+
needsPriming = false
|
|
165
|
+
return 0
|
|
166
|
+
}
|
|
167
|
+
silence.clear()
|
|
168
|
+
val count = write(silence)
|
|
169
|
+
check(count >= 0 && count % 2 == 0) { "AudioTrack priming failed ($count)" }
|
|
170
|
+
needsPriming = count == bufferBytes
|
|
171
|
+
return count / 2
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
override fun playbackHead(): Int = track.playbackHeadPosition
|
|
175
|
+
|
|
176
|
+
override fun underrunCount(): Int? =
|
|
177
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) track.underrunCount else null
|
|
178
|
+
|
|
179
|
+
override fun flush() {
|
|
180
|
+
track.pause()
|
|
181
|
+
track.flush()
|
|
182
|
+
needsPriming = Build.VERSION.SDK_INT < Build.VERSION_CODES.S
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
override fun release() {
|
|
66
186
|
try {
|
|
67
|
-
|
|
68
|
-
track
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
promise.resolve(null)
|
|
72
|
-
} catch (e: Exception) {
|
|
73
|
-
promise.reject("ERR_STOP", e)
|
|
187
|
+
track.pause()
|
|
188
|
+
track.flush()
|
|
189
|
+
} finally {
|
|
190
|
+
try { track.release() } finally { abandonFocus() }
|
|
74
191
|
}
|
|
75
192
|
}
|
|
76
193
|
}
|