Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEAT: changed play method to play growing files #2

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading