From 87de9b75e7ebe11f6346e48b7efbcfccf69a88b3 Mon Sep 17 00:00:00 2001 From: dudubenmoshe Date: Wed, 8 Jan 2025 14:47:32 +0200 Subject: [PATCH] FEAT: changed play method to play growing files --- mods/streams/src/AudioStream.ts | 43 ++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/mods/streams/src/AudioStream.ts b/mods/streams/src/AudioStream.ts index 3a12d25bf..8c1600201 100644 --- a/mods/streams/src/AudioStream.ts +++ b/mods/streams/src/AudioStream.ts @@ -32,6 +32,7 @@ class AudioStream { private stream: Readable; private socket: net.Socket; private isPlaying: boolean = true; + private shouldStopPlayback = false; /** * Creates a new AudioStream. @@ -70,7 +71,7 @@ class AudioStream { * @param {string} filePath - The path to the audio file * @return {Promise} */ - async play(filePath: string) { + async playStaticFile(filePath: string) { const fileStream = fs.readFileSync(filePath); let offset = 0; @@ -88,6 +89,46 @@ class AudioStream { } } + async play(filePath: string) { + let offset = 0; + let fileSize = 0; + + while (true) { + try { + const stats = fs.statSync(filePath); + fileSize = stats.size; + + if (offset < fileSize) { + const sliceSize = Math.min(fileSize - offset, MAX_CHUNK_SIZE); + const buffer = Buffer.alloc(sliceSize); + + const fd = fs.openSync(filePath, 'r'); + fs.readSync(fd, buffer, 0, sliceSize, offset); + fs.closeSync(fd); + + const messageBuffer = Message.createSlinMessage(buffer); + this.socket.write(messageBuffer); + + offset += sliceSize; + } + + // Wait for 20ms to match the sample rate + await setTimeout(20); + } catch (err) { + console.error("Error during playback:", err); + break; + } + + if (this.shouldStopPlayback) { + break; + } + } + } + + setShouldStopPlayback(condition: boolean) { + this.shouldStopPlayback = condition; + } + stopPlayback() { this.isPlaying = false; }