react-native-pcm-player-lite 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # react-native-pcm-player-lite
2
+
3
+ Tiny React Native native module to play **streaming 16‑bit PCM (mono, little‑endian)** with very low latency.
4
+ Works great for AI voice assistants that stream raw PCM over sockets.
5
+
6
+ - Android: `AudioTrack` streaming mode
7
+ - iOS: `AVAudioEngine` + `AVAudioPlayerNode` (converts Int16 -> Float32)
8
+
9
+ > ⚠️ Expects base64-encoded **Int16 LE** PCM chunks and a **fixed sample rate** (e.g., 24000).
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm i react-native-pcm-player-lite
15
+ # or
16
+ yarn add react-native-pcm-player-lite
17
+ ```
18
+
19
+ iOS:
20
+ ```bash
21
+ cd ios && pod install && cd ..
22
+ ```
23
+
24
+ Rebuild your app (Android/iOS). Autolinking will pick it up.
25
+
26
+ ## Usage
27
+
28
+ ```ts
29
+ import PCM from 'react-native-pcm-player-lite'
30
+
31
+ await PCM.start(24000) // start before first chunk
32
+
33
+ // For each audio chunk from your server (base64 Int16LE PCM):
34
+ PCM.enqueueBase64(chunkBase64)
35
+
36
+ // When the utterance/stream ends:
37
+ await PCM.stop()
38
+ ```
39
+
40
+ ### Chunk sizing
41
+ Send ~10–60 ms of audio per chunk:
42
+ - At 24 kHz mono, 10 ms = 240 samples = 480 bytes.
43
+ - At 24 kHz mono, 40 ms = 960 samples = 1920 bytes.
44
+
45
+ Too-small chunks can underrun; too-large chunks add latency.
46
+
47
+ ## API
48
+
49
+ - `start(sampleRate?: number): Promise<void>` – Start the audio engine and prepare streaming.
50
+ - `enqueueBase64(base64Chunk: string): void` – Push raw PCM data (base64 string).
51
+ - `stop(): Promise<void>` – Stop and release resources.
52
+
53
+ ## Troubleshooting
54
+
55
+ - **Silence?** Ensure your PCM is **16-bit little‑endian**, **mono**, and sample rate matches `start()`.
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.
58
+
59
+ ## License
60
+ MIT
@@ -0,0 +1,38 @@
1
+ buildscript {
2
+ repositories {
3
+ google()
4
+ mavenCentral()
5
+ }
6
+ dependencies {
7
+ classpath("com.android.tools.build:gradle:8.1.0")
8
+ }
9
+ }
10
+
11
+ apply plugin: "com.android.library"
12
+ apply plugin: "maven-publish"
13
+
14
+ android {
15
+ namespace "com.pcmplayer"
16
+ compileSdkVersion 34
17
+
18
+ defaultConfig {
19
+ minSdkVersion 21
20
+ targetSdkVersion 34
21
+ consumerProguardFiles "consumer-rules.pro"
22
+ }
23
+
24
+ publishing {
25
+ singleVariant("release") {
26
+ withSourcesJar()
27
+ }
28
+ }
29
+ }
30
+
31
+ repositories {
32
+ google()
33
+ mavenCentral()
34
+ }
35
+
36
+ dependencies {
37
+ implementation "com.facebook.react:react-android"
38
+ }
@@ -0,0 +1 @@
1
+ POM_ARTIFACT_ID=react-native-pcm-player-lite
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.pcmplayer">
2
+ <application />
3
+ </manifest>
@@ -0,0 +1,76 @@
1
+ package com.pcmplayer
2
+
3
+ import com.facebook.react.bridge.*
4
+ import android.media.AudioFormat
5
+ import android.media.AudioManager
6
+ import android.media.AudioTrack
7
+ import android.util.Base64
8
+ import java.util.concurrent.ArrayBlockingQueue
9
+ import kotlin.concurrent.thread
10
+
11
+ class PcmPlayerModule(reactContext: ReactApplicationContext) :
12
+ ReactContextBaseJavaModule(reactContext) {
13
+
14
+ private var track: AudioTrack? = null
15
+ private val queue = ArrayBlockingQueue<ByteArray>(64)
16
+ @Volatile private var playing = false
17
+
18
+ override fun getName() = "PcmPlayer"
19
+
20
+ @ReactMethod
21
+ fun start(sampleRate: Int, promise: Promise) {
22
+ try {
23
+ if (track != null) { promise.resolve(null); return }
24
+ val minBuf = AudioTrack.getMinBufferSize(
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)
53
+ }
54
+ }
55
+
56
+ @ReactMethod
57
+ fun enqueueBase64(b64: String) {
58
+ try {
59
+ val bytes = Base64.decode(b64, Base64.DEFAULT)
60
+ queue.offer(bytes)
61
+ } catch (_: Exception) {}
62
+ }
63
+
64
+ @ReactMethod
65
+ fun stop(promise: Promise) {
66
+ try {
67
+ playing = false
68
+ track?.let { it.stop(); it.release() }
69
+ track = null
70
+ queue.clear()
71
+ promise.resolve(null)
72
+ } catch (e: Exception) {
73
+ promise.reject("ERR_STOP", e)
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,14 @@
1
+ package com.pcmplayer
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class PcmPlayerPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
10
+ listOf(PcmPlayerModule(reactContext))
11
+
12
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
13
+ emptyList()
14
+ }
@@ -0,0 +1,70 @@
1
+ import Foundation
2
+ import AVFoundation
3
+
4
+ @objc(PcmPlayer)
5
+ class PcmPlayer: NSObject {
6
+
7
+ private let engine = AVAudioEngine()
8
+ private let player = AVAudioPlayerNode()
9
+ private var fmt: AVAudioFormat?
10
+ private var isStarted = false
11
+
12
+ @objc(start:withResolver:withRejecter:)
13
+ func start(sampleRate: NSNumber,
14
+ resolve: RCTPromiseResolveBlock,
15
+ reject: RCTPromiseRejectBlock) {
16
+ if isStarted { resolve(nil); return }
17
+ let sr = sampleRate.doubleValue
18
+ do {
19
+ try AVAudioSession.sharedInstance().setCategory(.playback, options: [.duckOthers])
20
+ try AVAudioSession.sharedInstance().setActive(true)
21
+ } catch {}
22
+
23
+ // Use float32 format and convert from Int16 manually.
24
+ fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sr, channels: 1, interleaved: true)
25
+
26
+ engine.attach(player)
27
+ engine.connect(player, to: engine.mainMixerNode, format: fmt)
28
+ do {
29
+ try engine.start()
30
+ player.play()
31
+ isStarted = true
32
+ resolve(nil)
33
+ } catch {
34
+ reject("ERR_START", "Failed to start audio engine", error)
35
+ }
36
+ }
37
+
38
+ @objc(enqueueBase64:)
39
+ func enqueueBase64(_ b64: NSString) {
40
+ guard isStarted, let fmt = fmt else { return }
41
+ guard let data = Data(base64Encoded: b64 as String) else { return }
42
+ let count = data.count / 2
43
+ var floats = [Float](repeating: 0, count: count)
44
+ data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in
45
+ let int16s = ptr.bindMemory(to: Int16.self)
46
+ for i in 0..<count {
47
+ floats[i] = Float(int16s[i]) / 32768.0
48
+ }
49
+ }
50
+ let frameCount = AVAudioFrameCount(count)
51
+ guard let buffer = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: frameCount) else { return }
52
+ buffer.frameLength = frameCount
53
+ let ch = buffer.floatChannelData![0]
54
+ floats.withUnsafeBufferPointer { src in
55
+ ch.assign(from: src.baseAddress!, count: count)
56
+ }
57
+ player.scheduleBuffer(buffer, completionHandler: nil)
58
+ }
59
+
60
+ @objc(stop:withRejecter:)
61
+ func stop(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
62
+ if !isStarted { resolve(nil); return }
63
+ player.stop()
64
+ engine.stop()
65
+ isStarted = false
66
+ resolve(nil)
67
+ }
68
+
69
+ @objc static func requiresMainQueueSetup() -> Bool { false }
70
+ }
@@ -0,0 +1,7 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ @interface RCT_EXTERN_MODULE(PcmPlayer, NSObject)
4
+ RCT_EXTERN_METHOD(start:(nonnull NSNumber *)sampleRate withResolver:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject)
5
+ RCT_EXTERN_METHOD(enqueueBase64:(NSString *)b64)
6
+ RCT_EXTERN_METHOD(stop:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject)
7
+ @end
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "react-native-pcm-player-lite",
3
+ "version": "0.1.0",
4
+ "description": "Ultra-small native module to play streaming 16-bit PCM (mono) in React Native (Android + iOS).",
5
+ "license": "MIT",
6
+ "author": "Anas Syed <me@anasyd.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/anasyd/react-native-pcm-player-lite.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/anasyd/react-native-pcm-player-lite/issues"
13
+ },
14
+ "keywords": [
15
+ "react-native",
16
+ "pcm",
17
+ "audio",
18
+ "audiotrack",
19
+ "avaudioengine",
20
+ "voice",
21
+ "streaming"
22
+ ],
23
+ "main": "src/index.js",
24
+ "types": "src/index.d.ts",
25
+ "react-native": "src/index.js",
26
+ "files": [
27
+ "src/**",
28
+ "android/**",
29
+ "ios/**",
30
+ "react-native-pcm-player-lite.podspec",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "peerDependencies": {
35
+ "react": ">=18.0.0",
36
+ "react-native": ">=0.71.0"
37
+ }
38
+ }
@@ -0,0 +1,17 @@
1
+ require "json"
2
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
3
+
4
+ Pod::Spec.new do |s|
5
+ s.name = "react-native-pcm-player-lite"
6
+ s.version = package["version"]
7
+ s.summary = package["description"]
8
+ s.license = { :type => "MIT" }
9
+ s.author = { "Your Name" => "you@example.com" }
10
+ s.homepage = package["repository"]["url"]
11
+ s.source = { :git => package["repository"]["url"], :tag => "v#{s.version}" }
12
+ s.platforms = { :ios => "12.0" }
13
+ s.source_files = "ios/**/*.{swift,m}"
14
+ s.requires_arc = true
15
+
16
+ s.dependency "React-Core"
17
+ end
package/src/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ declare module 'react-native-pcm-player-lite' {
2
+ /** Start the native PCM player at the given sample rate (e.g., 24000). */
3
+ export function start(sampleRate?: number): Promise<void>;
4
+ /** Enqueue a base64-encoded 16-bit LE PCM chunk (mono). */
5
+ export function enqueueBase64(base64Chunk: string): void;
6
+ /** Stop and release resources. */
7
+ export function stop(): Promise<void>;
8
+ const _default: { start: typeof start; enqueueBase64: typeof enqueueBase64; stop: typeof stop };
9
+ export default _default;
10
+ }
package/src/index.js ADDED
@@ -0,0 +1,37 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+ const LINKING_ERROR =
3
+ `The package 'react-native-pcm-player-lite' doesn't seem to be linked. Make sure: \n\n` +
4
+ (Platform.OS === 'ios' ? "- You have run 'pod install'\n" : '') +
5
+ '- You rebuilt the app after installing the package\n' +
6
+ '- You are not using Expo managed workflow (bare/with autolinking is fine)\n';
7
+
8
+ const PcmPlayer = NativeModules.PcmPlayer
9
+ ? NativeModules.PcmPlayer
10
+ : new Proxy({}, {
11
+ get() {
12
+ throw new Error(LINKING_ERROR);
13
+ },
14
+ });
15
+
16
+ /**
17
+ * Start the native PCM player.
18
+ * @param {number} sampleRate e.g., 24000
19
+ */
20
+ export function start(sampleRate = 24000) {
21
+ return PcmPlayer.start(sampleRate);
22
+ }
23
+
24
+ /**
25
+ * Enqueue a base64-encoded 16-bit little-endian PCM chunk (mono).
26
+ * Keep chunks around 10–60 ms of audio for best results.
27
+ */
28
+ export function enqueueBase64(b64) {
29
+ return PcmPlayer.enqueueBase64(b64);
30
+ }
31
+
32
+ /** Stop and release audio resources. */
33
+ export function stop() {
34
+ return PcmPlayer.stop();
35
+ }
36
+
37
+ export default { start, enqueueBase64, stop };