@octane-xplat/audio 0.0.0 → 0.7.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.
@@ -0,0 +1,2 @@
1
+ import { createAudioPlayer } from "./index2.js";
2
+ export { createAudioPlayer };
@@ -0,0 +1,206 @@
1
+ //#region src/audio.ios.ts
2
+ var createAudioPlayer = () => {
3
+ const listeners = /* @__PURE__ */ new Set();
4
+ const session = AVAudioSession.sharedInstance();
5
+ const hasMediaPlayer = typeof MPRemoteCommandCenter !== "undefined" && typeof MPNowPlayingInfoCenter !== "undefined" && typeof globalThis.MPNowPlayingInfoPropertyPlaybackDuration !== "undefined" && typeof globalThis.MPRemoteCommandHandlerStatus !== "undefined";
6
+ const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : void 0;
7
+ const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : void 0;
8
+ let queue = [];
9
+ let index = -1;
10
+ let player;
11
+ let state = "idle";
12
+ let error;
13
+ let disposed = false;
14
+ let wasPlayingBeforeInterruption = false;
15
+ let timer;
16
+ let endObserver;
17
+ let interruptionObserver;
18
+ const remoteTargets = [];
19
+ const current = () => queue[index];
20
+ const seconds = (time) => {
21
+ const value = CMTimeGetSeconds(time);
22
+ return Number.isFinite(value) && value > 0 ? value : 0;
23
+ };
24
+ const snapshot = () => ({
25
+ state,
26
+ track: current(),
27
+ currentTime: player ? seconds(player.currentTime()) : 0,
28
+ duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
29
+ error
30
+ });
31
+ const emit = () => {
32
+ const value = snapshot();
33
+ for (const listener of listeners) listener(value);
34
+ };
35
+ const updateNowPlaying = () => {
36
+ if (!nowPlaying) return;
37
+ const track = current();
38
+ if (!track) {
39
+ nowPlaying.nowPlayingInfo = null;
40
+ return;
41
+ }
42
+ const info = NSMutableDictionary.dictionary();
43
+ info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle);
44
+ if (track.artist) info.setObjectForKey(track.artist, MPMediaItemPropertyArtist);
45
+ if (track.album) info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle);
46
+ info.setObjectForKey(snapshot().duration, MPNowPlayingInfoPropertyPlaybackDuration);
47
+ info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime);
48
+ info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate);
49
+ nowPlaying.nowPlayingInfo = info;
50
+ };
51
+ const clearTrack = () => {
52
+ if (endObserver) {
53
+ NSNotificationCenter.defaultCenter.removeObserver(endObserver);
54
+ endObserver = void 0;
55
+ }
56
+ player?.pause();
57
+ player = void 0;
58
+ };
59
+ const load = async (autoplay = false) => {
60
+ clearTrack();
61
+ const track = current();
62
+ if (!track) {
63
+ state = "idle";
64
+ updateNowPlaying();
65
+ emit();
66
+ return;
67
+ }
68
+ state = "loading";
69
+ error = void 0;
70
+ emit();
71
+ try {
72
+ const url = track.source.startsWith("/") ? NSURL.fileURLWithPath(track.source) : NSURL.URLWithString(track.source);
73
+ const item = AVPlayerItem.playerItemWithURL(url);
74
+ player = AVPlayer.playerWithPlayerItem(item);
75
+ endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(AVPlayerItemDidPlayToEndTimeNotification, item, NSOperationQueue.mainQueue, () => void advance(1));
76
+ state = "paused";
77
+ updateNowPlaying();
78
+ emit();
79
+ if (autoplay) await play();
80
+ } catch (cause) {
81
+ error = cause instanceof Error ? cause : new Error(String(cause));
82
+ state = "error";
83
+ emit();
84
+ throw error;
85
+ }
86
+ };
87
+ const advance = async (delta) => {
88
+ if (!queue.length || disposed) return;
89
+ if (index + delta >= queue.length) {
90
+ state = "ended";
91
+ player?.pause();
92
+ emit();
93
+ return;
94
+ }
95
+ index = Math.max(0, index + delta);
96
+ await load(true);
97
+ };
98
+ const play = async () => {
99
+ if (!player || disposed) return;
100
+ const category = AVAudioSessionCategoryPlayback;
101
+ session.setCategoryModeOptionsError(category, AVAudioSessionModeDefault, 0, null);
102
+ session.setActiveWithOptionsError(true, 0, null);
103
+ player.play();
104
+ state = "playing";
105
+ updateNowPlaying();
106
+ emit();
107
+ };
108
+ const addRemoteTarget = (command, handler) => {
109
+ const token = command.addTargetWithHandler((event) => {
110
+ handler(event);
111
+ return MPRemoteCommandHandlerStatus.Success;
112
+ });
113
+ remoteTargets.push({
114
+ command,
115
+ token
116
+ });
117
+ };
118
+ if (commandCenter) {
119
+ addRemoteTarget(commandCenter.playCommand, () => void play());
120
+ addRemoteTarget(commandCenter.pauseCommand, () => void pause());
121
+ addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1));
122
+ addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1));
123
+ addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
124
+ if (player && Number.isFinite(event.positionTime)) {
125
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600));
126
+ updateNowPlaying();
127
+ emit();
128
+ }
129
+ });
130
+ }
131
+ interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(AVAudioSessionInterruptionNotification, null, NSOperationQueue.mainQueue, (notification) => {
132
+ if (notification.userInfo.objectForKey(AVAudioSessionInterruptionTypeKey).unsignedIntegerValue === AVAudioSessionInterruptionType.Began) {
133
+ wasPlayingBeforeInterruption = state === "playing";
134
+ player?.pause();
135
+ state = "paused";
136
+ emit();
137
+ } else if (wasPlayingBeforeInterruption) {
138
+ const options = notification.userInfo.objectForKey(AVAudioSessionInterruptionOptionKey)?.unsignedIntegerValue ?? 0;
139
+ wasPlayingBeforeInterruption = false;
140
+ if ((options & AVAudioSessionInterruptionOptionShouldResume) !== 0) play();
141
+ }
142
+ });
143
+ return {
144
+ capabilities: () => ({
145
+ supported: true,
146
+ backgroundPlayback: true,
147
+ systemControls: hasMediaPlayer,
148
+ userGestureRequired: false,
149
+ interruptions: true
150
+ }),
151
+ snapshot,
152
+ subscribe: (listener) => {
153
+ listeners.add(listener);
154
+ listener(snapshot());
155
+ timer ??= setInterval(() => {
156
+ updateNowPlaying();
157
+ emit();
158
+ }, 500);
159
+ return () => {
160
+ listeners.delete(listener);
161
+ if (!listeners.size && timer) {
162
+ clearInterval(timer);
163
+ timer = void 0;
164
+ }
165
+ };
166
+ },
167
+ setQueue: async (tracks, startAt = 0) => {
168
+ if (disposed) throw new Error("AudioPlayer is disposed");
169
+ queue = [...tracks];
170
+ index = queue.length ? Math.max(0, Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1)) : -1;
171
+ await load();
172
+ },
173
+ play,
174
+ pause: async () => {
175
+ player?.pause();
176
+ state = "paused";
177
+ updateNowPlaying();
178
+ emit();
179
+ },
180
+ seek: async (value) => {
181
+ if (!player || !Number.isFinite(value)) return;
182
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600));
183
+ updateNowPlaying();
184
+ emit();
185
+ },
186
+ dispose: () => {
187
+ if (disposed) return;
188
+ disposed = true;
189
+ clearTrack();
190
+ if (interruptionObserver) NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver);
191
+ interruptionObserver = void 0;
192
+ for (const { command, token } of remoteTargets) command.removeTarget(token);
193
+ remoteTargets.length = 0;
194
+ if (timer) clearInterval(timer);
195
+ timer = void 0;
196
+ if (nowPlaying) nowPlaying.nowPlayingInfo = null;
197
+ session.setActiveWithOptionsError(false, AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation, null);
198
+ listeners.clear();
199
+ queue = [];
200
+ index = -1;
201
+ state = "idle";
202
+ }
203
+ };
204
+ };
205
+ //#endregion
206
+ export { createAudioPlayer };
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 1,
3
+ "buildId": "efa30128-f454-4503-bd0f-58c33a1b6971",
4
+ "mode": "production",
5
+ "capabilities": {
6
+ "independentHydration": false
7
+ }
8
+ }
@@ -0,0 +1,2 @@
1
+ import { createAudioPlayer } from "./index2.js";
2
+ export { createAudioPlayer };
@@ -0,0 +1,136 @@
1
+ //#region src/audio.web.ts
2
+ var createAudioPlayer = () => {
3
+ const audio = new Audio();
4
+ const listeners = /* @__PURE__ */ new Set();
5
+ let queue = [];
6
+ let index = -1;
7
+ let state = "idle";
8
+ let error;
9
+ let disposed = false;
10
+ const current = () => queue[index];
11
+ const snapshot = () => ({
12
+ state,
13
+ track: current(),
14
+ currentTime: audio.currentTime || 0,
15
+ duration: Number.isFinite(audio.duration) ? audio.duration : 0,
16
+ error
17
+ });
18
+ const emit = () => {
19
+ const value = snapshot();
20
+ for (const listener of listeners) listener(value);
21
+ };
22
+ const setTrack = () => {
23
+ const track = current();
24
+ if (!track) {
25
+ audio.removeAttribute("src");
26
+ state = "idle";
27
+ emit();
28
+ return;
29
+ }
30
+ audio.src = track.source;
31
+ state = "loading";
32
+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
33
+ navigator.mediaSession.metadata = new MediaMetadata({
34
+ title: track.title ?? track.id,
35
+ artist: track.artist ?? "",
36
+ album: track.album ?? ""
37
+ });
38
+ navigator.mediaSession.setActionHandler("play", () => {
39
+ audio.play();
40
+ });
41
+ navigator.mediaSession.setActionHandler("pause", () => audio.pause());
42
+ navigator.mediaSession.setActionHandler("seekto", (event) => {
43
+ if (event.seekTime != null) audio.currentTime = event.seekTime;
44
+ });
45
+ navigator.mediaSession.setActionHandler("nexttrack", () => {
46
+ advance(1);
47
+ });
48
+ navigator.mediaSession.setActionHandler("previoustrack", () => {
49
+ advance(-1);
50
+ });
51
+ }
52
+ emit();
53
+ };
54
+ const advance = async (delta) => {
55
+ if (!queue.length) return;
56
+ if (delta > 0 && index + 1 >= queue.length) {
57
+ audio.pause();
58
+ state = "ended";
59
+ emit();
60
+ return;
61
+ }
62
+ index = Math.max(0, Math.min(index + delta, queue.length - 1));
63
+ setTrack();
64
+ try {
65
+ await audio.play();
66
+ } catch (cause) {
67
+ error = cause instanceof Error ? cause : new Error(String(cause));
68
+ state = "error";
69
+ emit();
70
+ }
71
+ };
72
+ for (const event of [
73
+ "timeupdate",
74
+ "durationchange",
75
+ "play",
76
+ "pause",
77
+ "ended",
78
+ "waiting",
79
+ "error"
80
+ ]) audio.addEventListener(event, () => {
81
+ if (event === "play") state = "playing";
82
+ else if (event === "pause" && state !== "ended") state = "paused";
83
+ else if (event === "ended") {
84
+ state = "ended";
85
+ advance(1);
86
+ return;
87
+ } else if (event === "error") {
88
+ state = "error";
89
+ error = /* @__PURE__ */ new Error("Audio playback failed");
90
+ } else if (event === "waiting") state = "loading";
91
+ emit();
92
+ });
93
+ return {
94
+ capabilities: () => ({
95
+ supported: true,
96
+ backgroundPlayback: false,
97
+ systemControls: typeof navigator !== "undefined" && "mediaSession" in navigator,
98
+ userGestureRequired: true,
99
+ interruptions: false,
100
+ reason: "Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture."
101
+ }),
102
+ snapshot,
103
+ subscribe: (listener) => {
104
+ listeners.add(listener);
105
+ listener(snapshot());
106
+ return () => listeners.delete(listener);
107
+ },
108
+ setQueue: async (tracks, startAt = 0) => {
109
+ if (disposed) throw new Error("AudioPlayer is disposed");
110
+ queue = [...tracks];
111
+ index = queue.length ? Math.min(Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0), queue.length - 1) : -1;
112
+ error = void 0;
113
+ setTrack();
114
+ },
115
+ play: async () => {
116
+ if (!disposed && current()) await audio.play();
117
+ },
118
+ pause: async () => {
119
+ audio.pause();
120
+ },
121
+ seek: async (seconds) => {
122
+ if (Number.isFinite(seconds)) audio.currentTime = Math.max(0, seconds);
123
+ },
124
+ dispose: () => {
125
+ disposed = true;
126
+ audio.pause();
127
+ audio.removeAttribute("src");
128
+ audio.load();
129
+ listeners.clear();
130
+ queue = [];
131
+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) navigator.mediaSession.metadata = null;
132
+ }
133
+ };
134
+ };
135
+ //#endregion
136
+ export { createAudioPlayer };
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 1,
3
+ "buildId": "0ccce776-27fc-48a4-82d6-3fe722075224",
4
+ "mode": "production",
5
+ "capabilities": {
6
+ "independentHydration": false
7
+ }
8
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
- "name": "@octane-xplat/audio",
3
- "version": "0.0.0",
4
- "description": "Stub reserving the name; real releases publish from CI via trusted publishing.",
5
- "publishConfig": {"access": "public"}
6
- }
2
+ "name": "@octane-xplat/audio",
3
+ "version": "0.7.0",
4
+ "description": "Long-form audio playback for Octane xplat",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/octane-xplat/octane-xplat.git",
8
+ "directory": "packages/audio"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "types",
13
+ "src",
14
+ "platforms"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./types/index.d.ts",
20
+ "web": "./dist/web/index.js",
21
+ "native": "./dist/native/index.js",
22
+ "default": "./dist/native/index.js"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "devDependencies": {
29
+ "@nativescript-community/octane": "0.2.1",
30
+ "@nativescript/core": "9.1.2",
31
+ "@octanejs/vite-plugin": "0.1.61",
32
+ "octane": "0.6.3",
33
+ "typescript": "5.9.3",
34
+ "vite": "8.3.0"
35
+ },
36
+ "peerDependencies": {
37
+ "@nativescript-community/octane": ">=0.2.1 <1",
38
+ "@nativescript/core": ">=9.1.0 <10",
39
+ "octane": ">=0.6.3 <1"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@nativescript-community/octane": {
43
+ "optional": true
44
+ },
45
+ "@nativescript/core": {
46
+ "optional": true
47
+ },
48
+ "octane": {
49
+ "optional": true
50
+ }
51
+ },
52
+ "nativescript": {
53
+ "platforms": {
54
+ "android": "9.1.0",
55
+ "ios": "9.1.0"
56
+ }
57
+ },
58
+ "scripts": {
59
+ "build": "vite build && vite build --mode native && tsc -p tsconfig.types.json && node ../../scripts/check-native-dist.mjs"
60
+ }
61
+ }
@@ -0,0 +1,15 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
4
+
5
+ <application>
6
+ <service
7
+ android:name="com.xplat.audio.AudioPlaybackService"
8
+ android:exported="true"
9
+ android:foregroundServiceType="mediaPlayback">
10
+ <intent-filter>
11
+ <action android:name="androidx.media3.session.MediaSessionService" />
12
+ </intent-filter>
13
+ </service>
14
+ </application>
15
+ </manifest>
Binary file
@@ -0,0 +1,8 @@
1
+ repositories {
2
+ mavenCentral()
3
+ }
4
+
5
+ dependencies {
6
+ implementation "androidx.media3:media3-exoplayer:1.9.3"
7
+ implementation "androidx.media3:media3-session:1.9.3"
8
+ }
@@ -0,0 +1,28 @@
1
+ package com.xplat.audio;
2
+
3
+ import android.content.Context;
4
+ import android.content.Intent;
5
+
6
+ /** Commands cross the JS/service boundary as intents so they remain ordered. */
7
+ public final class AudioBridge {
8
+ public static final String ACTION_QUEUE = "com.xplat.audio.QUEUE";
9
+ public static final String ACTION_PLAY = "com.xplat.audio.PLAY";
10
+ public static final String ACTION_PAUSE = "com.xplat.audio.PAUSE";
11
+ public static final String ACTION_SEEK = "com.xplat.audio.SEEK";
12
+ public static final String ACTION_RELEASE = "com.xplat.audio.RELEASE";
13
+ private static volatile String snapshot = "{\"state\":\"idle\",\"currentTime\":0,\"duration\":0}";
14
+
15
+ private AudioBridge() {}
16
+
17
+ public static void dispatch(Context context, String action, String payload, int index, double seconds) {
18
+ Intent intent = new Intent(context.getApplicationContext(), AudioPlaybackService.class);
19
+ intent.setAction(action);
20
+ if (payload != null) intent.putExtra("queue", payload);
21
+ intent.putExtra("index", index);
22
+ intent.putExtra("seconds", seconds);
23
+ context.getApplicationContext().startService(intent);
24
+ }
25
+
26
+ public static void publish(String value) { snapshot = value; }
27
+ public static String snapshot() { return snapshot; }
28
+ }
@@ -0,0 +1,115 @@
1
+ package com.xplat.audio;
2
+
3
+ import android.content.Intent;
4
+ import android.net.Uri;
5
+ import java.io.File;
6
+ import android.os.IBinder;
7
+ import android.util.Log;
8
+
9
+ import androidx.media3.common.AudioAttributes;
10
+ import androidx.media3.common.MediaItem;
11
+ import androidx.media3.common.MediaMetadata;
12
+ import androidx.media3.common.PlaybackException;
13
+ import androidx.media3.common.Player;
14
+ import androidx.media3.exoplayer.ExoPlayer;
15
+ import androidx.media3.session.MediaSession;
16
+ import androidx.media3.session.MediaSessionService;
17
+
18
+ import org.json.JSONArray;
19
+ import org.json.JSONObject;
20
+
21
+ public final class AudioPlaybackService extends MediaSessionService {
22
+ private static final String TAG = "XplatAudio";
23
+ private ExoPlayer player;
24
+ private MediaSession session;
25
+ private Player.Listener listener;
26
+ private String error;
27
+
28
+ @Override public void onCreate() {
29
+ super.onCreate();
30
+ player = new ExoPlayer.Builder(this).build();
31
+ player.setAudioAttributes(AudioAttributes.DEFAULT, true);
32
+ listener = new Player.Listener() {
33
+ @Override public void onEvents(Player p, Player.Events events) { publishSnapshot(); }
34
+ @Override public void onPlayerError(PlaybackException exception) {
35
+ error = exception.getMessage();
36
+ publishSnapshot();
37
+ }
38
+ };
39
+ player.addListener(listener);
40
+ session = new MediaSession.Builder(this, player).build();
41
+ publishSnapshot();
42
+ }
43
+
44
+ @Override public MediaSession onGetSession(MediaSession.ControllerInfo controllerInfo) { return session; }
45
+
46
+ @Override public int onStartCommand(Intent intent, int flags, int startId) {
47
+ int result = super.onStartCommand(intent, flags, startId);
48
+ if (intent == null || intent.getAction() == null) return result;
49
+ try {
50
+ switch (intent.getAction()) {
51
+ case AudioBridge.ACTION_QUEUE:
52
+ setQueue(intent.getStringExtra("queue"), intent.getIntExtra("index", 0));
53
+ break;
54
+ case AudioBridge.ACTION_PLAY: player.play(); break;
55
+ case AudioBridge.ACTION_PAUSE: player.pause(); break;
56
+ case AudioBridge.ACTION_SEEK: player.seekTo((long) (intent.getDoubleExtra("seconds", 0) * 1000)); break;
57
+ case AudioBridge.ACTION_RELEASE:
58
+ player.stop();
59
+ player.clearMediaItems();
60
+ stopSelf();
61
+ break;
62
+ }
63
+ } catch (Exception cause) {
64
+ Log.e(TAG, "Audio command failed", cause);
65
+ error = cause.getMessage();
66
+ publishSnapshot();
67
+ }
68
+ return result;
69
+ }
70
+
71
+ private void setQueue(String encoded, int startAt) throws Exception {
72
+ JSONArray queue = new JSONArray(encoded == null ? "[]" : encoded);
73
+ player.clearMediaItems();
74
+ error = null;
75
+ for (int i = 0; i < queue.length(); i++) {
76
+ JSONObject track = queue.getJSONObject(i);
77
+ String source = track.getString("source");
78
+ MediaMetadata metadata = new MediaMetadata.Builder()
79
+ .setTitle(track.optString("title", track.optString("id", "")))
80
+ .setArtist(track.optString("artist", ""))
81
+ .setAlbumTitle(track.optString("album", ""))
82
+ .build();
83
+ Uri uri = source.startsWith("/") ? Uri.fromFile(new File(source)) : Uri.parse(source);
84
+ player.addMediaItem(new MediaItem.Builder().setUri(uri).setMediaMetadata(metadata).build());
85
+ }
86
+ if (queue.length() > 0) player.seekTo(Math.max(0, Math.min(startAt, queue.length() - 1)), 0);
87
+ player.prepare();
88
+ publishSnapshot();
89
+ }
90
+
91
+ private void publishSnapshot() {
92
+ try {
93
+ JSONObject value = new JSONObject();
94
+ int index = player == null ? -1 : player.getCurrentMediaItemIndex();
95
+ value.put("state", error != null ? "error" : player == null || player.getMediaItemCount() == 0 ? "idle" : player.getPlaybackState() == Player.STATE_ENDED ? "ended" : player.isPlaying() ? "playing" : player.getPlaybackState() == Player.STATE_BUFFERING ? "loading" : "paused");
96
+ value.put("index", index);
97
+ value.put("currentTime", player == null ? 0 : Math.max(0, player.getCurrentPosition()) / 1000.0);
98
+ value.put("duration", player == null || player.getDuration() < 0 ? 0 : player.getDuration() / 1000.0);
99
+ if (error != null) value.put("error", error);
100
+ AudioBridge.publish(value.toString());
101
+ } catch (Exception ignored) { }
102
+ }
103
+
104
+ @Override public void onDestroy() {
105
+ if (player != null) {
106
+ player.removeListener(listener);
107
+ player.release();
108
+ }
109
+ if (session != null) session.release();
110
+ AudioBridge.publish("{\"state\":\"idle\",\"currentTime\":0,\"duration\":0}");
111
+ super.onDestroy();
112
+ }
113
+
114
+ @Override public IBinder onBind(Intent intent) { return super.onBind(intent); }
115
+ }
@@ -0,0 +1,5 @@
1
+ // MediaPlayer.framework supplies MPNowPlayingInfoCenter / MPRemoteCommandCenter
2
+ // and the MPNowPlayingInfoProperty* keys used by the iOS lock-screen transport
3
+ // integration. Without the explicit link, JS symbol lookups fail at runtime
4
+ // (ReferenceError: MPNowPlayingInfoPropertyPlaybackDuration is not defined).
5
+ OTHER_LDFLAGS = $(inherited) -framework "MediaPlayer"
@@ -0,0 +1,100 @@
1
+ import { Utils } from "@nativescript/core";
2
+ import type {
3
+ AudioCapabilities,
4
+ AudioPlayer,
5
+ AudioSnapshot,
6
+ Track,
7
+ } from "./types";
8
+
9
+ export const createAudioPlayer = (): AudioPlayer => {
10
+ const actions = com.xplat.audio.AudioBridge;
11
+ const context = Utils.android.getApplicationContext();
12
+ const listeners = new Set<(snapshot: AudioSnapshot) => void>();
13
+ let queue: Track[] = [];
14
+ let index = -1;
15
+ let disposed = false;
16
+ let poll: ReturnType<typeof setInterval> | undefined;
17
+
18
+ const snapshot = (): AudioSnapshot => {
19
+ const value = JSON.parse(actions.snapshot()) as {
20
+ state: AudioSnapshot["state"];
21
+ index?: number;
22
+ currentTime?: number;
23
+ duration?: number;
24
+ error?: string;
25
+ };
26
+
27
+ if (Number.isInteger(value.index) && value.index! >= 0) {index = value.index!;}
28
+ return {
29
+ state: value.state,
30
+ track: queue[index],
31
+ currentTime: value.currentTime ?? 0,
32
+ duration: value.duration ?? 0,
33
+ error: value.error ? new Error(value.error) : undefined,
34
+ };
35
+ };
36
+
37
+ const emit = () => {
38
+ const value = snapshot();
39
+ for (const listener of listeners) {listener(value);}
40
+ };
41
+
42
+ const dispatch = (action: string, payload = "", at = 0, seconds = 0) => {
43
+ if (disposed) {throw new Error("AudioPlayer is disposed");}
44
+ actions.dispatch(context, action, payload, at, seconds);
45
+ };
46
+
47
+ const ensurePolling = () => {
48
+ if (listeners.size && !poll) {poll = setInterval(emit, 250);}
49
+ if (!listeners.size && poll) {
50
+ clearInterval(poll);
51
+ poll = undefined;
52
+ }
53
+ };
54
+
55
+ return {
56
+ capabilities: (): AudioCapabilities => ({
57
+ supported: true,
58
+ backgroundPlayback: true,
59
+ systemControls: true,
60
+ userGestureRequired: false,
61
+ interruptions: true,
62
+ }),
63
+ snapshot,
64
+ subscribe: (listener) => {
65
+ listeners.add(listener);
66
+ listener(snapshot());
67
+ ensurePolling();
68
+ return () => {
69
+ listeners.delete(listener);
70
+ ensurePolling();
71
+ };
72
+ },
73
+ setQueue: async (tracks, startAt = 0) => {
74
+ if (disposed) {throw new Error("AudioPlayer is disposed");}
75
+ queue = [...tracks];
76
+ index = queue.length
77
+ ? Math.max(0, Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1))
78
+ : -1;
79
+
80
+ dispatch(actions.ACTION_QUEUE, JSON.stringify(queue), index);
81
+ emit();
82
+ },
83
+ play: async () => dispatch(actions.ACTION_PLAY),
84
+ pause: async () => dispatch(actions.ACTION_PAUSE),
85
+ seek: async (seconds) => {
86
+ if (Number.isFinite(seconds)) {dispatch(actions.ACTION_SEEK, "", 0, Math.max(0, seconds));}
87
+ emit();
88
+ },
89
+ dispose: () => {
90
+ if (disposed) {return;}
91
+ disposed = true;
92
+ actions.dispatch(context, actions.ACTION_RELEASE, "", 0, 0);
93
+ if (poll) {clearInterval(poll);}
94
+ poll = undefined;
95
+ listeners.clear();
96
+ queue = [];
97
+ index = -1;
98
+ },
99
+ };
100
+ };
@@ -0,0 +1,255 @@
1
+ import type {
2
+ AudioCapabilities,
3
+ AudioPlayer,
4
+ AudioSnapshot,
5
+ Track,
6
+ } from "./types";
7
+
8
+ export const createAudioPlayer = (): AudioPlayer => {
9
+ const listeners = new Set<(snapshot: AudioSnapshot) => void>();
10
+ const session = AVAudioSession.sharedInstance();
11
+ // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
12
+ // needs MediaPlayer.framework linked AND metadata-generated — plugin
13
+ // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
14
+ // undefined. Playback still works; guard and report systemControls:false.
15
+ const hasMediaPlayer =
16
+ typeof MPRemoteCommandCenter !== 'undefined' &&
17
+ typeof MPNowPlayingInfoCenter !== 'undefined' &&
18
+ // Metadata constants/enums don't get TS declarations — probe via globalThis.
19
+ typeof (globalThis as any).MPNowPlayingInfoPropertyPlaybackDuration !== 'undefined' &&
20
+ typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined';
21
+
22
+ const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined;
23
+ const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined;
24
+ let queue: Track[] = [];
25
+ let index = -1;
26
+ let player: AVPlayer | undefined;
27
+ let state: AudioSnapshot["state"] = "idle";
28
+ let error: Error | undefined;
29
+ let disposed = false;
30
+ let wasPlayingBeforeInterruption = false;
31
+ let timer: ReturnType<typeof setInterval> | undefined;
32
+ let endObserver: NSObjectProtocol | undefined;
33
+ let interruptionObserver: NSObjectProtocol | undefined;
34
+ const remoteTargets: Array<{ command: any; token: any }> = [];
35
+
36
+ const current = () => queue[index];
37
+ const seconds = (time: CMTime) => {
38
+ const value = CMTimeGetSeconds(time);
39
+ return Number.isFinite(value) && value > 0 ? value : 0;
40
+ };
41
+
42
+ const snapshot = (): AudioSnapshot => ({
43
+ state,
44
+ track: current(),
45
+ currentTime: player ? seconds(player.currentTime()) : 0,
46
+ duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
47
+ error,
48
+ });
49
+
50
+ const emit = () => {
51
+ const value = snapshot();
52
+ for (const listener of listeners) {listener(value);}
53
+ };
54
+
55
+ const updateNowPlaying = () => {
56
+ if (!nowPlaying) {return;}
57
+ const track = current();
58
+ if (!track) {
59
+ nowPlaying.nowPlayingInfo = null;
60
+ return;
61
+ }
62
+
63
+ const info = NSMutableDictionary.dictionary();
64
+ info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle);
65
+ if (track.artist) {info.setObjectForKey(track.artist, MPMediaItemPropertyArtist);}
66
+ if (track.album) {info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle);}
67
+ info.setObjectForKey(snapshot().duration, MPNowPlayingInfoPropertyPlaybackDuration);
68
+ info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime);
69
+ info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate);
70
+ nowPlaying.nowPlayingInfo = info;
71
+ };
72
+
73
+ const clearTrack = () => {
74
+ if (endObserver) {
75
+ NSNotificationCenter.defaultCenter.removeObserver(endObserver);
76
+ endObserver = undefined;
77
+ }
78
+
79
+ player?.pause();
80
+ player = undefined;
81
+ };
82
+
83
+ const load = async (autoplay = false) => {
84
+ clearTrack();
85
+ const track = current();
86
+ if (!track) {
87
+ state = "idle";
88
+ updateNowPlaying();
89
+ emit();
90
+ return;
91
+ }
92
+
93
+ state = "loading";
94
+ error = undefined;
95
+ emit();
96
+ try {
97
+ const url = track.source.startsWith("/")
98
+ ? NSURL.fileURLWithPath(track.source)
99
+ : NSURL.URLWithString(track.source);
100
+
101
+ const item = AVPlayerItem.playerItemWithURL(url);
102
+ player = AVPlayer.playerWithPlayerItem(item);
103
+ endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
104
+ AVPlayerItemDidPlayToEndTimeNotification,
105
+ item,
106
+ NSOperationQueue.mainQueue,
107
+ () => void advance(1),
108
+ );
109
+
110
+ state = "paused";
111
+ updateNowPlaying();
112
+ emit();
113
+ if (autoplay) {await play();}
114
+ } catch (cause) {
115
+ error = cause instanceof Error ? cause : new Error(String(cause));
116
+ state = "error";
117
+ emit();
118
+ throw error;
119
+ }
120
+ };
121
+
122
+ const advance = async (delta: number) => {
123
+ if (!queue.length || disposed) {return;}
124
+ if (index + delta >= queue.length) {
125
+ state = "ended";
126
+ player?.pause();
127
+ emit();
128
+ return;
129
+ }
130
+
131
+ index = Math.max(0, index + delta);
132
+ await load(true);
133
+ };
134
+
135
+ const play = async () => {
136
+ if (!player || disposed) {return;}
137
+ const category = AVAudioSessionCategoryPlayback;
138
+ session.setCategoryModeOptionsError(category, AVAudioSessionModeDefault, 0, null);
139
+ session.setActiveWithOptionsError(true, 0, null);
140
+ player.play();
141
+ state = "playing";
142
+ updateNowPlaying();
143
+ emit();
144
+ };
145
+
146
+ const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
147
+ const token = command.addTargetWithHandler((event: any) => {
148
+ handler(event);
149
+ return MPRemoteCommandHandlerStatus.Success;
150
+ });
151
+
152
+ remoteTargets.push({ command, token });
153
+ };
154
+
155
+ if (commandCenter) {
156
+ addRemoteTarget(commandCenter.playCommand, () => void play());
157
+ addRemoteTarget(commandCenter.pauseCommand, () => void pause());
158
+ addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1));
159
+ addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1));
160
+ addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
161
+ if (player && Number.isFinite(event.positionTime)) {
162
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600));
163
+ updateNowPlaying();
164
+ emit();
165
+ }
166
+ });
167
+ }
168
+
169
+ interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
170
+ AVAudioSessionInterruptionNotification,
171
+ null,
172
+ NSOperationQueue.mainQueue,
173
+ (notification) => {
174
+ const type = notification.userInfo.objectForKey(AVAudioSessionInterruptionTypeKey).unsignedIntegerValue;
175
+ if (type === AVAudioSessionInterruptionType.Began) {
176
+ wasPlayingBeforeInterruption = state === "playing";
177
+ player?.pause();
178
+ state = "paused";
179
+ emit();
180
+ } else if (wasPlayingBeforeInterruption) {
181
+ const options = notification.userInfo.objectForKey(AVAudioSessionInterruptionOptionKey)?.unsignedIntegerValue ?? 0;
182
+ wasPlayingBeforeInterruption = false;
183
+ if ((options & AVAudioSessionInterruptionOptionShouldResume) !== 0) {
184
+ void play();
185
+ }
186
+ }
187
+ },
188
+ );
189
+
190
+ return {
191
+ capabilities: (): AudioCapabilities => ({
192
+ supported: true,
193
+ backgroundPlayback: true,
194
+ systemControls: hasMediaPlayer,
195
+ userGestureRequired: false,
196
+ interruptions: true,
197
+ }),
198
+ snapshot,
199
+ subscribe: (listener) => {
200
+ listeners.add(listener);
201
+ listener(snapshot());
202
+ timer ??= setInterval(() => {
203
+ updateNowPlaying();
204
+ emit();
205
+ }, 500);
206
+
207
+ return () => {
208
+ listeners.delete(listener);
209
+ if (!listeners.size && timer) {
210
+ clearInterval(timer);
211
+ timer = undefined;
212
+ }
213
+ };
214
+ },
215
+ setQueue: async (tracks, startAt = 0) => {
216
+ if (disposed) {throw new Error("AudioPlayer is disposed");}
217
+ queue = [...tracks];
218
+ index = queue.length
219
+ ? Math.max(0, Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1))
220
+ : -1;
221
+
222
+ await load();
223
+ },
224
+ play,
225
+ pause: async () => {
226
+ player?.pause();
227
+ state = "paused";
228
+ updateNowPlaying();
229
+ emit();
230
+ },
231
+ seek: async (value) => {
232
+ if (!player || !Number.isFinite(value)) {return;}
233
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600));
234
+ updateNowPlaying();
235
+ emit();
236
+ },
237
+ dispose: () => {
238
+ if (disposed) {return;}
239
+ disposed = true;
240
+ clearTrack();
241
+ if (interruptionObserver) {NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver);}
242
+ interruptionObserver = undefined;
243
+ for (const { command, token } of remoteTargets) {command.removeTarget(token);}
244
+ remoteTargets.length = 0;
245
+ if (timer) {clearInterval(timer);}
246
+ timer = undefined;
247
+ if (nowPlaying) {nowPlaying.nowPlayingInfo = null;}
248
+ session.setActiveWithOptionsError(false, AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation, null);
249
+ listeners.clear();
250
+ queue = [];
251
+ index = -1;
252
+ state = "idle";
253
+ },
254
+ };
255
+ };
package/src/audio.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Application } from "@nativescript/core";
2
+ import { createAudioPlayer as createAndroidAudioPlayer } from "./audio.android";
3
+ import { createAudioPlayer as createIOSAudioPlayer } from "./audio.ios";
4
+ import type { AudioPlayer } from "./types";
5
+
6
+ export const createAudioPlayer = (): AudioPlayer => {
7
+ if (Application.android) {return createAndroidAudioPlayer();}
8
+ if (Application.ios) {return createIOSAudioPlayer();}
9
+ throw new Error("@octane-xplat/audio requires iOS or Android");
10
+ };
@@ -0,0 +1,183 @@
1
+ import type {
2
+ AudioCapabilities,
3
+ AudioPlayer,
4
+ AudioSnapshot,
5
+ Track,
6
+ } from "./types";
7
+
8
+ export const createAudioPlayer = (): AudioPlayer => {
9
+ const audio = new Audio();
10
+ const listeners = new Set<(value: AudioSnapshot) => void>();
11
+ let queue: Track[] = [];
12
+ let index = -1;
13
+ let state: AudioSnapshot["state"] = "idle";
14
+ let error: Error | undefined;
15
+ let disposed = false;
16
+ const current = () => queue[index];
17
+ const snapshot = (): AudioSnapshot => ({
18
+ state,
19
+ track: current(),
20
+ currentTime: audio.currentTime || 0,
21
+ duration: Number.isFinite(audio.duration) ? audio.duration : 0,
22
+ error,
23
+ });
24
+
25
+ const emit = () => {
26
+ const value = snapshot();
27
+ for (const listener of listeners) {
28
+ listener(value);
29
+ }
30
+ };
31
+
32
+ const setTrack = () => {
33
+ const track = current();
34
+ if (!track) {
35
+ audio.removeAttribute("src");
36
+ state = "idle";
37
+ emit();
38
+ return;
39
+ }
40
+
41
+ audio.src = track.source;
42
+ state = "loading";
43
+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
44
+ navigator.mediaSession.metadata = new MediaMetadata({
45
+ title: track.title ?? track.id,
46
+ artist: track.artist ?? "",
47
+ album: track.album ?? "",
48
+ });
49
+
50
+ navigator.mediaSession.setActionHandler("play", () => {
51
+ void audio.play();
52
+ });
53
+
54
+ navigator.mediaSession.setActionHandler("pause", () => audio.pause());
55
+ navigator.mediaSession.setActionHandler("seekto", (event) => {
56
+ if (event.seekTime != null) {
57
+ audio.currentTime = event.seekTime;
58
+ }
59
+ });
60
+
61
+ navigator.mediaSession.setActionHandler("nexttrack", () => {
62
+ void advance(1);
63
+ });
64
+
65
+ navigator.mediaSession.setActionHandler("previoustrack", () => {
66
+ void advance(-1);
67
+ });
68
+ }
69
+
70
+ emit();
71
+ };
72
+
73
+ const advance = async (delta: number) => {
74
+ if (!queue.length) {
75
+ return;
76
+ }
77
+
78
+ if (delta > 0 && index + 1 >= queue.length) {
79
+ audio.pause();
80
+ state = "ended";
81
+ emit();
82
+ return;
83
+ }
84
+
85
+ index = Math.max(0, Math.min(index + delta, queue.length - 1));
86
+ setTrack();
87
+ try {
88
+ await audio.play();
89
+ } catch (cause) {
90
+ error = cause instanceof Error ? cause : new Error(String(cause));
91
+ state = "error";
92
+ emit();
93
+ }
94
+ };
95
+
96
+ for (const event of [
97
+ "timeupdate",
98
+ "durationchange",
99
+ "play",
100
+ "pause",
101
+ "ended",
102
+ "waiting",
103
+ "error",
104
+ ]) {
105
+ audio.addEventListener(event, () => {
106
+ if (event === "play") {
107
+ state = "playing";
108
+ } else if (event === "pause" && state !== "ended") {
109
+ state = "paused";
110
+ } else if (event === "ended") {
111
+ state = "ended";
112
+ void advance(1);
113
+ return;
114
+ } else if (event === "error") {
115
+ state = "error";
116
+ error = new Error("Audio playback failed");
117
+ } else if (event === "waiting") {
118
+ state = "loading";
119
+ }
120
+
121
+ emit();
122
+ });
123
+ }
124
+
125
+ return {
126
+ capabilities: (): AudioCapabilities => ({
127
+ supported: true,
128
+ backgroundPlayback: false,
129
+ systemControls:
130
+ typeof navigator !== "undefined" && "mediaSession" in navigator,
131
+ userGestureRequired: true,
132
+ interruptions: false,
133
+ reason:
134
+ "Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture.",
135
+ }),
136
+ snapshot,
137
+ subscribe: (listener) => {
138
+ listeners.add(listener);
139
+ listener(snapshot());
140
+ return () => listeners.delete(listener);
141
+ },
142
+ setQueue: async (tracks, startAt = 0) => {
143
+ if (disposed) {
144
+ throw new Error("AudioPlayer is disposed");
145
+ }
146
+
147
+ queue = [...tracks];
148
+ index = queue.length
149
+ ? Math.min(
150
+ Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0),
151
+ queue.length - 1,
152
+ )
153
+ : -1;
154
+
155
+ error = undefined;
156
+ setTrack();
157
+ },
158
+ play: async () => {
159
+ if (!disposed && current()) {
160
+ await audio.play();
161
+ }
162
+ },
163
+ pause: async () => {
164
+ audio.pause();
165
+ },
166
+ seek: async (seconds) => {
167
+ if (Number.isFinite(seconds)) {
168
+ audio.currentTime = Math.max(0, seconds);
169
+ }
170
+ },
171
+ dispose: () => {
172
+ disposed = true;
173
+ audio.pause();
174
+ audio.removeAttribute("src");
175
+ audio.load();
176
+ listeners.clear();
177
+ queue = [];
178
+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
179
+ navigator.mediaSession.metadata = null;
180
+ }
181
+ },
182
+ };
183
+ };
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./types";
2
+ export { createAudioPlayer } from "./audio";
@@ -0,0 +1,2 @@
1
+ export * from "./types";
2
+ export { createAudioPlayer } from "./audio.web";
package/src/types.ts ADDED
@@ -0,0 +1,42 @@
1
+ export type Track = {
2
+ id: string;
3
+ source: string;
4
+ title?: string;
5
+ artist?: string;
6
+ album?: string;
7
+ };
8
+
9
+ export type AudioCapabilities = {
10
+ supported: boolean;
11
+ backgroundPlayback: boolean;
12
+ systemControls: boolean;
13
+ userGestureRequired: boolean;
14
+ interruptions: boolean;
15
+ reason?: string;
16
+ };
17
+
18
+ export type PlaybackState =
19
+ "idle" | "loading" | "playing" | "paused" | "ended" | "error";
20
+
21
+ export type AudioSnapshot = {
22
+ state: PlaybackState;
23
+ track?: Track;
24
+ /** Current position in seconds. */
25
+ currentTime: number;
26
+ /** Track length in seconds, or 0 until known. */
27
+ duration: number;
28
+ error?: Error;
29
+ };
30
+
31
+ export interface AudioPlayer {
32
+ capabilities(): AudioCapabilities;
33
+ snapshot(): AudioSnapshot;
34
+ subscribe(listener: (snapshot: AudioSnapshot) => void): () => void;
35
+ setQueue(tracks: readonly Track[], startAt?: number): Promise<void>;
36
+ play(): Promise<void>;
37
+ pause(): Promise<void>;
38
+ seek(seconds: number): Promise<void>;
39
+ dispose(): void;
40
+ }
41
+
42
+ export declare function createAudioPlayer(): AudioPlayer;
@@ -0,0 +1 @@
1
+ export * from "./types";
@@ -0,0 +1,36 @@
1
+ export type Track = {
2
+ id: string;
3
+ source: string;
4
+ title?: string;
5
+ artist?: string;
6
+ album?: string;
7
+ };
8
+ export type AudioCapabilities = {
9
+ supported: boolean;
10
+ backgroundPlayback: boolean;
11
+ systemControls: boolean;
12
+ userGestureRequired: boolean;
13
+ interruptions: boolean;
14
+ reason?: string;
15
+ };
16
+ export type PlaybackState = "idle" | "loading" | "playing" | "paused" | "ended" | "error";
17
+ export type AudioSnapshot = {
18
+ state: PlaybackState;
19
+ track?: Track;
20
+ /** Current position in seconds. */
21
+ currentTime: number;
22
+ /** Track length in seconds, or 0 until known. */
23
+ duration: number;
24
+ error?: Error;
25
+ };
26
+ export interface AudioPlayer {
27
+ capabilities(): AudioCapabilities;
28
+ snapshot(): AudioSnapshot;
29
+ subscribe(listener: (snapshot: AudioSnapshot) => void): () => void;
30
+ setQueue(tracks: readonly Track[], startAt?: number): Promise<void>;
31
+ play(): Promise<void>;
32
+ pause(): Promise<void>;
33
+ seek(seconds: number): Promise<void>;
34
+ dispose(): void;
35
+ }
36
+ export declare function createAudioPlayer(): AudioPlayer;