@fonoster/streams 0.15.20 → 0.16.3

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,38 @@
1
+ import * as net from "net";
2
+ import { Readable } from "stream";
3
+ /**
4
+ * @classdesc Object representing an audio player that can play audio files and streams.
5
+ */
6
+ export declare class AudioPlayer {
7
+ private activeStream;
8
+ private socket;
9
+ private isPlaying;
10
+ private currentSessionId;
11
+ /**
12
+ * Creates a new AudioPlayer.
13
+ *
14
+ * @param {net.Socket} socket - A TCP socket for writing audio data
15
+ */
16
+ constructor(socket: net.Socket);
17
+ /**
18
+ * Utility for playing audio files.
19
+ *
20
+ * @param {string} filePath - The path to the audio file
21
+ * @return {Promise<void>}
22
+ */
23
+ play(filePath: string): Promise<void>;
24
+ /**
25
+ * Plays audio from an input stream and returns an output stream.
26
+ * The playback can be stopped using stopPlayStream().
27
+ *
28
+ * @param {Readable} inputStream - The input stream to read audio from
29
+ * @return {Promise<void>}
30
+ */
31
+ playStream(inputStream: Readable): Promise<void>;
32
+ /**
33
+ * Stops the current stream playback.
34
+ */
35
+ stop(): void;
36
+ private _processAudioChunk;
37
+ private _cleanupActiveStream;
38
+ }
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.AudioPlayer = void 0;
46
+ /**
47
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
48
+ * http://github.com/fonoster/fonoster
49
+ *
50
+ * This file is part of Fonoster
51
+ *
52
+ * Licensed under the MIT License (the "License");
53
+ * you may not use this file except in compliance with
54
+ * the License. You may obtain a copy of the License at
55
+ *
56
+ * https://opensource.org/licenses/MIT
57
+ *
58
+ * Unless required by applicable law or agreed to in writing, software
59
+ * distributed under the License is distributed on an "AS IS" BASIS,
60
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
61
+ * See the License for the specific language governing permissions and
62
+ * limitations under the License.
63
+ */
64
+ const fs = __importStar(require("fs"));
65
+ const promises_1 = require("node:timers/promises");
66
+ const stream_1 = require("stream");
67
+ const logger_1 = require("@fonoster/logger");
68
+ const Message_1 = require("./Message");
69
+ const logger = (0, logger_1.getLogger)({ service: "streams", filePath: __filename });
70
+ const MAX_CHUNK_SIZE = 320;
71
+ /**
72
+ * @classdesc Object representing an audio player that can play audio files and streams.
73
+ */
74
+ class AudioPlayer {
75
+ /**
76
+ * Creates a new AudioPlayer.
77
+ *
78
+ * @param {net.Socket} socket - A TCP socket for writing audio data
79
+ */
80
+ constructor(socket) {
81
+ this.activeStream = null;
82
+ this.isPlaying = false;
83
+ this.currentSessionId = 0;
84
+ this.socket = socket;
85
+ }
86
+ /**
87
+ * Utility for playing audio files.
88
+ *
89
+ * @param {string} filePath - The path to the audio file
90
+ * @return {Promise<void>}
91
+ */
92
+ play(filePath) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ logger.verbose("playing audio file", { filePath });
95
+ const fileData = fs.readFileSync(filePath);
96
+ return this.playStream(stream_1.Readable.from(fileData));
97
+ });
98
+ }
99
+ /**
100
+ * Plays audio from an input stream and returns an output stream.
101
+ * The playback can be stopped using stopPlayStream().
102
+ *
103
+ * @param {Readable} inputStream - The input stream to read audio from
104
+ * @return {Promise<void>}
105
+ */
106
+ playStream(inputStream) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ // Stop any currently playing stream before starting a new one
109
+ this.stop();
110
+ this.isPlaying = true;
111
+ // Increment session ID to invalidate any in-flight processing from previous streams
112
+ const sessionId = ++this.currentSessionId;
113
+ this.activeStream = inputStream;
114
+ const buffer = [];
115
+ let isProcessing = false;
116
+ const processBuffer = () => __awaiter(this, void 0, void 0, function* () {
117
+ // Check both isPlaying AND that this session is still current
118
+ if (!this.isPlaying ||
119
+ sessionId !== this.currentSessionId ||
120
+ isProcessing ||
121
+ buffer.length === 0)
122
+ return;
123
+ isProcessing = true;
124
+ try {
125
+ while (buffer.length > 0 &&
126
+ this.isPlaying &&
127
+ sessionId === this.currentSessionId) {
128
+ const chunk = buffer.shift();
129
+ yield this._processAudioChunk(chunk);
130
+ }
131
+ }
132
+ finally {
133
+ isProcessing = false;
134
+ }
135
+ });
136
+ return new Promise((resolve, reject) => {
137
+ inputStream.on("data", (chunk) => __awaiter(this, void 0, void 0, function* () {
138
+ // Check session ID to ensure this stream is still active
139
+ if (!this.isPlaying || sessionId !== this.currentSessionId)
140
+ return;
141
+ for (let offset = 0; offset < chunk.length; offset += MAX_CHUNK_SIZE) {
142
+ const sliceSize = Math.min(chunk.length - offset, MAX_CHUNK_SIZE);
143
+ const slicedChunk = chunk.subarray(offset, offset + sliceSize);
144
+ buffer.push(slicedChunk);
145
+ }
146
+ if (!isProcessing) {
147
+ yield processBuffer();
148
+ resolve();
149
+ }
150
+ }));
151
+ inputStream.on("error", (err) => {
152
+ logger.error("error playing stream", err);
153
+ this._cleanupActiveStream();
154
+ reject(err);
155
+ });
156
+ inputStream.on("end", () => {
157
+ this._cleanupActiveStream();
158
+ });
159
+ });
160
+ });
161
+ }
162
+ /**
163
+ * Stops the current stream playback.
164
+ */
165
+ stop() {
166
+ this.isPlaying = false;
167
+ this._cleanupActiveStream();
168
+ }
169
+ _processAudioChunk(chunk) {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ const buffer = Message_1.Message.createSlinMessage(chunk);
172
+ this.socket.write(buffer);
173
+ yield (0, promises_1.setTimeout)(20);
174
+ });
175
+ }
176
+ _cleanupActiveStream() {
177
+ if (this.activeStream) {
178
+ this.activeStream.removeAllListeners("data");
179
+ this.activeStream.removeAllListeners("error");
180
+ this.activeStream.removeAllListeners("end");
181
+ this.activeStream.pause();
182
+ this.activeStream = null;
183
+ }
184
+ }
185
+ }
186
+ exports.AudioPlayer = AudioPlayer;
@@ -1,9 +1,28 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
1
19
  import * as net from "net";
2
20
  import { Readable } from "stream";
3
21
  /**
4
22
  * @classdesc Object representing a stream of bidirectional audio data and control messages.
5
23
  */
6
24
  declare class AudioStream {
25
+ private player;
7
26
  private stream;
8
27
  private socket;
9
28
  /**
@@ -30,6 +49,18 @@ declare class AudioStream {
30
49
  * @return {Promise<void>}
31
50
  */
32
51
  play(filePath: string): Promise<void>;
52
+ /**
53
+ * Plays audio from an input stream and returns an output stream.
54
+ * The playback can be stopped using stopPlayStream().
55
+ *
56
+ * @param {Readable} inputStream - The input stream to read audio from
57
+ * @return {Promise<void>}
58
+ */
59
+ playStream(inputStream: Readable): Promise<void>;
60
+ /**
61
+ * Stops the current stream playback.
62
+ */
63
+ stop(): void;
33
64
  /**
34
65
  * Adds a listener for the data event.
35
66
  *
@@ -1,37 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -43,29 +10,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
43
10
  };
44
11
  Object.defineProperty(exports, "__esModule", { value: true });
45
12
  exports.AudioStream = void 0;
46
- /**
47
- * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
48
- * http://github.com/fonoster/fonoster
49
- *
50
- * This file is part of Fonoster
51
- *
52
- * Licensed under the MIT License (the "License");
53
- * you may not use this file except in compliance with
54
- * the License. You may obtain a copy of the License at
55
- *
56
- * https://opensource.org/licenses/MIT
57
- *
58
- * Unless required by applicable law or agreed to in writing, software
59
- * distributed under the License is distributed on an "AS IS" BASIS,
60
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
61
- * See the License for the specific language governing permissions and
62
- * limitations under the License.
63
- */
64
- const fs = __importStar(require("fs"));
65
- const promises_1 = require("node:timers/promises");
13
+ const AudioPlayer_1 = require("./AudioPlayer");
66
14
  const Message_1 = require("./Message");
67
15
  const types_1 = require("./types");
68
- const MAX_CHUNK_SIZE = 320;
69
16
  /**
70
17
  * @classdesc Object representing a stream of bidirectional audio data and control messages.
71
18
  */
@@ -79,6 +26,7 @@ class AudioStream {
79
26
  constructor(stream, socket) {
80
27
  this.stream = stream;
81
28
  this.socket = socket;
29
+ this.player = new AudioPlayer_1.AudioPlayer(socket);
82
30
  }
83
31
  /**
84
32
  * Writes media data to the stream.
@@ -106,20 +54,27 @@ class AudioStream {
106
54
  */
107
55
  play(filePath) {
108
56
  return __awaiter(this, void 0, void 0, function* () {
109
- const fileStream = fs.readFileSync(filePath);
110
- let offset = 0;
111
- // eslint-disable-next-line no-loops/no-loops
112
- while (offset < fileStream.length) {
113
- const sliceSize = Math.min(fileStream.length - offset, MAX_CHUNK_SIZE);
114
- const slicedChunk = fileStream.subarray(offset, offset + sliceSize);
115
- const buffer = Message_1.Message.createSlinMessage(slicedChunk);
116
- this.socket.write(buffer);
117
- offset += sliceSize;
118
- // Wait for 20ms to match the sample rate
119
- yield (0, promises_1.setTimeout)(20);
120
- }
57
+ return this.player.play(filePath);
121
58
  });
122
59
  }
60
+ /**
61
+ * Plays audio from an input stream and returns an output stream.
62
+ * The playback can be stopped using stopPlayStream().
63
+ *
64
+ * @param {Readable} inputStream - The input stream to read audio from
65
+ * @return {Promise<void>}
66
+ */
67
+ playStream(inputStream) {
68
+ return __awaiter(this, void 0, void 0, function* () {
69
+ return this.player.playStream(inputStream);
70
+ });
71
+ }
72
+ /**
73
+ * Stops the current stream playback.
74
+ */
75
+ stop() {
76
+ this.player.stop();
77
+ }
123
78
  /**
124
79
  * Adds a listener for the data event.
125
80
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fonoster/streams",
3
- "version": "0.15.20",
3
+ "version": "0.16.3",
4
4
  "description": "Core support for Fonoster Streams",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/fonoster#readme",
@@ -18,7 +18,7 @@
18
18
  "generate:readme": "node ../../.scripts/gen-readme.cjs"
19
19
  },
20
20
  "dependencies": {
21
- "@fonoster/logger": "^0.15.20",
21
+ "@fonoster/logger": "^0.16.0",
22
22
  "uuid": "^11.0.3"
23
23
  },
24
24
  "devDependencies": {
@@ -37,5 +37,5 @@
37
37
  "bugs": {
38
38
  "url": "https://github.com/fonoster/fonoster/issues"
39
39
  },
40
- "gitHead": "65a0a5c60b7401e949e90af22db5a74ca37a601e"
40
+ "gitHead": "0bdf9d00ecd86af2d2a0e93bd427f2e52ab55f95"
41
41
  }