Skip to content

Commit

Permalink
Merge pull request #2 from VoicenterTeam/voice-route
Browse files Browse the repository at this point in the history
FEAT: changed play method to play growing files
  • Loading branch information
bohdan-duda authored Jan 8, 2025
2 parents 9338f47 + 87de9b7 commit 27d168e
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion mods/streams/src/AudioStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class AudioStream {
private stream: Readable;
private socket: net.Socket;
private isPlaying: boolean = true;
private shouldStopPlayback = false;

/**
* Creates a new AudioStream.
Expand Down Expand Up @@ -70,7 +71,7 @@ class AudioStream {
* @param {string} filePath - The path to the audio file
* @return {Promise<void>}
*/
async play(filePath: string) {
async playStaticFile(filePath: string) {
const fileStream = fs.readFileSync(filePath);

let offset = 0;
Expand All @@ -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;
}
Expand Down

0 comments on commit 27d168e

Please sign in to comment.