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.
@@ -1,84 +1,100 @@
1
- import Foundation
2
1
  import AVFoundation
3
- import React // <- This imports RCTPromiseResolveBlock / RCTPromiseRejectBlock
2
+ import Foundation
3
+ import React
4
4
 
5
5
  @objc(PcmPlayer)
6
- class PcmPlayer: NSObject {
6
+ final class PcmPlayer: RCTEventEmitter {
7
+ private let playback = PcmPlayback(makeRenderer: PcmAudioRenderer.init)
7
8
 
8
- private let engine = AVAudioEngine()
9
- private let player = AVAudioPlayerNode()
10
- private var fmt: AVAudioFormat?
11
- private var isStarted = false
9
+ private var interruptionObserver: NSObjectProtocol?
12
10
 
13
- @objc(start:withResolver:withRejecter:)
14
- func start(sampleRate: NSNumber,
15
- resolve: RCTPromiseResolveBlock,
16
- reject: RCTPromiseRejectBlock) {
17
- if isStarted {
18
- resolve(NSNull()) // avoid 'nil requires a contextual type'
19
- return
11
+ override init() {
12
+ super.init()
13
+ interruptionObserver = NotificationCenter.default.addObserver(
14
+ forName: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance(), queue: nil
15
+ ) { [weak self] note in
16
+ guard let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
17
+ let type = AVAudioSession.InterruptionType(rawValue: raw) else { return }
18
+ let options = note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0
19
+ self?.playback.queue.async { [weak self] in
20
+ switch type {
21
+ case .began: self?.playback.interruptionBegan()
22
+ case .ended: self?.playback.interruptionEnded(shouldResume:
23
+ AVAudioSession.InterruptionOptions(rawValue: options).contains(.shouldResume))
24
+ @unknown default: break
25
+ }
26
+ }
20
27
  }
21
- let sr = sampleRate.doubleValue
28
+ }
22
29
 
23
- do {
24
- try AVAudioSession.sharedInstance().setCategory(.playback, options: [.duckOthers])
25
- try AVAudioSession.sharedInstance().setActive(true)
26
- } catch {
27
- // don't fail hard on session issues; TTS still likely works
28
- }
30
+ deinit {
31
+ if let observer = interruptionObserver { NotificationCenter.default.removeObserver(observer) }
32
+ }
33
+
34
+ override var methodQueue: DispatchQueue { playback.queue }
29
35
 
30
- // Use float32 format; we’ll feed converted int16 -> float32
31
- fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sr, channels: 1, interleaved: true)
36
+ override func supportedEvents() -> [String]! { ["PcmPlayerEvent"] }
32
37
 
33
- engine.attach(player)
34
- engine.connect(player, to: engine.mainMixerNode, format: fmt)
35
- do {
36
- try engine.start()
37
- player.play()
38
- isStarted = true
39
- resolve(NSNull())
40
- } catch {
41
- reject("ERR_START", "Failed to start audio engine", error)
38
+ override func startObserving() {
39
+ playback.sync {
40
+ playback.emit = { [weak self] type, message in
41
+ var body = ["type": type]
42
+ body["message"] = message
43
+ self?.sendEvent(withName: "PcmPlayerEvent", body: body)
44
+ }
42
45
  }
43
46
  }
44
47
 
45
- @objc(enqueueBase64:)
46
- func enqueueBase64(_ b64: NSString) {
47
- guard isStarted, let fmt = fmt else { return }
48
- guard let data = Data(base64Encoded: b64 as String) else { return }
48
+ override func stopObserving() {
49
+ playback.sync { playback.emit = nil }
50
+ }
49
51
 
50
- // Convert Int16 LE -> Float32
51
- let count = data.count / 2
52
- var floats = [Float](repeating: 0, count: count)
53
- data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in
54
- let int16s = ptr.bindMemory(to: Int16.self)
55
- for i in 0..<count {
56
- floats[i] = Float(int16s[i]) / 32768.0
57
- }
52
+ override func invalidate() {
53
+ playback.sync {
54
+ super.invalidate()
55
+ playback.stop()
58
56
  }
57
+ }
59
58
 
60
- let frameCount = AVAudioFrameCount(count)
61
- guard let buffer = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: frameCount) else { return }
62
- buffer.frameLength = frameCount
63
- let ch = buffer.floatChannelData![0]
64
- floats.withUnsafeBufferPointer { src in
65
- ch.assign(from: src.baseAddress!, count: count)
59
+ @objc(start:policy:withResolver:withRejecter:)
60
+ func start(sampleRate: NSNumber, policy: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
61
+ playback.sync {
62
+ do {
63
+ try playback.start(sampleRate, preserve: policy == "preserve")
64
+ resolve(nil)
65
+ } catch PcmPlaybackError.invalidRate {
66
+ reject("ERR_INVALID_RATE", PcmPlaybackError.invalidRate.localizedDescription, nil)
67
+ } catch {
68
+ reject("ERR_START", "Failed to start PCM playback", error)
69
+ }
66
70
  }
71
+ }
67
72
 
68
- player.scheduleBuffer(buffer, completionHandler: nil)
73
+ @objc(enqueueBase64:)
74
+ func enqueueBase64(_ base64: String) {
75
+ playback.sync { playback.enqueue(base64) }
69
76
  }
70
77
 
71
78
  @objc(stop:withRejecter:)
72
79
  func stop(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
73
- if !isStarted {
74
- resolve(NSNull())
75
- return
80
+ playback.sync {
81
+ playback.stop()
82
+ resolve(nil)
76
83
  }
77
- player.stop()
78
- engine.stop()
79
- isStarted = false
80
- resolve(NSNull())
81
84
  }
82
85
 
83
- @objc static func requiresMainQueueSetup() -> Bool { false }
86
+ @objc(flush:withRejecter:)
87
+ func flush(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
88
+ playback.sync {
89
+ playback.flush()
90
+ resolve(nil)
91
+ }
92
+ }
93
+
94
+ @objc(getStatus:withRejecter:)
95
+ func getStatus(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
96
+ playback.sync { resolve(playback.status) }
97
+ }
98
+
99
+ @objc override static func requiresMainQueueSetup() -> Bool { false }
84
100
  }
@@ -1,10 +1,16 @@
1
1
  #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTEventEmitter.h>
2
3
 
3
- @interface RCT_EXTERN_MODULE(PcmPlayer, NSObject)
4
+ @interface RCT_EXTERN_MODULE(PcmPlayer, RCTEventEmitter)
4
5
  RCT_EXTERN_METHOD(start:(nonnull NSNumber *)sampleRate
6
+ policy:(NSString *)policy
5
7
  withResolver:(RCTPromiseResolveBlock)resolve
6
8
  withRejecter:(RCTPromiseRejectBlock)reject)
7
- RCT_EXTERN_METHOD(enqueueBase64:(NSString *)b64)
9
+ RCT_EXTERN_METHOD(enqueueBase64:(nonnull NSString *)base64)
8
10
  RCT_EXTERN_METHOD(stop:(RCTPromiseResolveBlock)resolve
9
11
  withRejecter:(RCTPromiseRejectBlock)reject)
12
+ RCT_EXTERN_METHOD(flush:(RCTPromiseResolveBlock)resolve
13
+ withRejecter:(RCTPromiseRejectBlock)reject)
14
+ RCT_EXTERN_METHOD(getStatus:(RCTPromiseResolveBlock)resolve
15
+ withRejecter:(RCTPromiseRejectBlock)reject)
10
16
  @end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-pcm-player-lite",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Ultra-small native module to play streaming 16-bit PCM (mono) in React Native (Android + iOS).",
5
5
  "license": "MIT",
6
6
  "author": "Anas Syed <me@anasyd.com>",
@@ -34,5 +34,12 @@
34
34
  "peerDependencies": {
35
35
  "react": ">=18.0.0",
36
36
  "react-native": ">=0.71.0"
37
+ },
38
+ "scripts": {
39
+ "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test --experimental-test-coverage --test-coverage-include=src/index.js --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 test/api.test.mjs",
40
+ "typecheck": "tsc -p test/tsconfig.json"
41
+ },
42
+ "devDependencies": {
43
+ "typescript": "~7.0.2"
37
44
  }
38
45
  }
@@ -6,7 +6,7 @@ Pod::Spec.new do |s|
6
6
  s.version = package["version"]
7
7
  s.summary = package["description"]
8
8
  s.license = { :type => "MIT" }
9
- s.author = { "Your Name" => "you@example.com" }
9
+ s.author = package["author"]
10
10
  s.homepage = package["repository"]["url"]
11
11
  s.source = { :git => package["repository"]["url"], :tag => "v#{s.version}" }
12
12
  s.platforms = { :ios => "12.0" }
package/src/index.d.ts CHANGED
@@ -1,10 +1,45 @@
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;
1
+ export interface PcmPlayerStartOptions {
2
+ sampleRate?: number;
3
+ channels?: 1;
4
+ interruptionPolicy?: 'preserve' | 'discard';
10
5
  }
6
+
7
+ export interface PcmPlayerStatus {
8
+ state: 'interrupted' | 'stopped' | 'playing' | 'idle';
9
+ queueDepth: number;
10
+ }
11
+
12
+ export interface PcmPlayerEvent {
13
+ type: 'started' | 'interrupted' | 'drained' | 'underrun' | 'error';
14
+ message?: string;
15
+ }
16
+
17
+ export interface PcmPlayerSubscription {
18
+ remove(): void;
19
+ }
20
+
21
+ /** Start mono playback at an integer rate from 8000 to 96000 Hz. Defaults to 24000 Hz. */
22
+ export function start(config?: number | PcmPlayerStartOptions): Promise<void>;
23
+ /** Enqueue a base64-encoded 16-bit little-endian PCM chunk (mono). */
24
+ export function enqueueBase64(base64Chunk: string): void;
25
+ /** Enqueue raw PCM bytes or a base64-encoded PCM chunk. */
26
+ export function enqueue(chunk: string | Uint8Array | ArrayBuffer): void;
27
+ /** Stop playback and release audio resources. */
28
+ export function stop(): Promise<void>;
29
+ /** Discard queued audio. */
30
+ export function flush(): Promise<void>;
31
+ /** Read the native playback state and queue depth. */
32
+ export function getStatus(): Promise<PcmPlayerStatus>;
33
+ /** Subscribe to playback events. */
34
+ export function addListener(listener: (event: PcmPlayerEvent) => void): PcmPlayerSubscription;
35
+
36
+ declare const pcmPlayer: {
37
+ start: typeof start;
38
+ enqueueBase64: typeof enqueueBase64;
39
+ enqueue: typeof enqueue;
40
+ stop: typeof stop;
41
+ flush: typeof flush;
42
+ getStatus: typeof getStatus;
43
+ addListener: typeof addListener;
44
+ };
45
+ export default pcmPlayer;
package/src/index.js CHANGED
@@ -1,37 +1,105 @@
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. */
1
+ import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
2
+
3
+ const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4
+ const DEFAULT_SAMPLE_RATE = 24000;
5
+
6
+ let emitter;
7
+
8
+ function getNativePlayer() {
9
+ const player = NativeModules.PcmPlayer;
10
+ if (!player) {
11
+ throw new Error(
12
+ "The package 'react-native-pcm-player-lite' doesn't seem to be linked. Make sure: \n\n" +
13
+ (Platform.OS === 'ios' ? "- You have run 'pod install'\n" : '') +
14
+ '- You rebuilt the app after installing the package\n' +
15
+ '- For Expo, use a development build and rebuild after installation. Expo Go does not include this module.\n',
16
+ );
17
+ }
18
+ return player;
19
+ }
20
+
21
+ function encodeBase64(bytes) {
22
+ const chunks = [];
23
+ let chunk = '';
24
+ for (let offset = 0; offset < bytes.length; offset += 3) {
25
+ const first = bytes[offset];
26
+ const second = bytes[offset + 1] ?? 0;
27
+ const third = bytes[offset + 2] ?? 0;
28
+
29
+ chunk += BASE64[first >> 2];
30
+ chunk += BASE64[((first & 3) << 4) | (second >> 4)];
31
+ chunk += offset + 1 < bytes.length ? BASE64[((second & 15) << 2) | (third >> 6)] : '=';
32
+ chunk += offset + 2 < bytes.length ? BASE64[third & 63] : '=';
33
+
34
+ if (chunk.length === 8192) {
35
+ chunks.push(chunk);
36
+ chunk = '';
37
+ }
38
+ }
39
+ chunks.push(chunk);
40
+ return chunks.join('');
41
+ }
42
+
43
+ /** Start playback at a sample rate in Hz, or with mono playback options. */
44
+ export function start(config = DEFAULT_SAMPLE_RATE) {
45
+ const player = getNativePlayer();
46
+ let sampleRate = config;
47
+ let interruptionPolicy = 'preserve';
48
+ if (config !== null && typeof config === 'object') {
49
+ const { sampleRate: rate = DEFAULT_SAMPLE_RATE, channels = 1 } = config;
50
+ if (channels !== 1) {
51
+ return Promise.reject(new RangeError('Only mono PCM is supported. Set channels to 1.'));
52
+ }
53
+ interruptionPolicy = config.interruptionPolicy === undefined ? 'preserve' : config.interruptionPolicy;
54
+ if (!['preserve', 'discard'].includes(interruptionPolicy)) {
55
+ return Promise.reject(new RangeError('interruptionPolicy must be preserve or discard.'));
56
+ }
57
+ sampleRate = rate;
58
+ }
59
+ if (!Number.isInteger(sampleRate) || sampleRate < 8000 || sampleRate > 96000) {
60
+ return Promise.reject(new RangeError('sampleRate must be an integer from 8000 to 96000 Hz.'));
61
+ }
62
+ return player.start(sampleRate, interruptionPolicy);
63
+ }
64
+
65
+ /** Enqueue base64-encoded 16-bit little-endian PCM (mono). */
66
+ export function enqueueBase64(base64Chunk) {
67
+ getNativePlayer().enqueueBase64(base64Chunk);
68
+ }
69
+
70
+ /** Enqueue the visible bytes of a PCM chunk or forward a base64 string. */
71
+ export function enqueue(chunk) {
72
+ if (typeof chunk === 'string') {
73
+ enqueueBase64(chunk);
74
+ return;
75
+ }
76
+ const bytes = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : chunk;
77
+ if (!(bytes instanceof Uint8Array)) {
78
+ throw new TypeError('Expected a base64 string, Uint8Array, or ArrayBuffer.');
79
+ }
80
+ enqueueBase64(encodeBase64(bytes));
81
+ }
82
+
83
+ /** Stop playback and release audio resources. */
33
84
  export function stop() {
34
- return PcmPlayer.stop();
85
+ return getNativePlayer().stop();
86
+ }
87
+
88
+ /** Discard queued audio. */
89
+ export function flush() {
90
+ return getNativePlayer().flush();
91
+ }
92
+
93
+ /** Read the native playback state and queue depth. */
94
+ export function getStatus() {
95
+ return getNativePlayer().getStatus();
96
+ }
97
+
98
+ /** Subscribe to playback events. Call remove() on the returned subscription. */
99
+ export function addListener(listener) {
100
+ const player = getNativePlayer();
101
+ emitter ??= new NativeEventEmitter(player);
102
+ return emitter.addListener('PcmPlayerEvent', listener);
35
103
  }
36
104
 
37
- export default { start, enqueueBase64, stop };
105
+ export default { start, enqueueBase64, enqueue, stop, flush, getStatus, addListener };