SAMPLE_RATE = 48000;
CHANNELS = 2;
BYTES_PER_SAMPLE = 2;
FRAME_SIZE = 960;
const audioStream = this.connection.receiver.subscribe(userId, {
end: { behavior: EndBehaviorType.Manual }
});
const fileStream = createWriteStream(tempPcmFile);
const opusDecoder = new prism.opus.Decoder({
frameSize: this.FRAME_SIZE,
channels: this.CHANNELS,
rate: this.SAMPLE_RATE
});
const decodedStream = audioStream.pipe(opusDecoder);
let loggedFirstAudio = false;
decodedStream.on('data', (pcmData: Buffer) => {
const currentTime = Date.now();
const timeSinceLastAudio = currentTime - recording.lastProcessedTime;
recording.lastProcessedTime = currentTime;
// fill the gap from last time spoken by the user
if (timeSinceLastAudio > 50) {
const silenceBuffer = this.createSilenceBuffer(timeSinceLastAudio);
fileStream.write(silenceBuffer);
}
if (this.paused) {
const silenceChunk = Buffer.alloc(pcmData.length);
fileStream.write(silenceChunk);
} else {
recording.hasReceivedAudio = true;
fileStream.write(pcmData);
}
});
private createSilenceBuffer(durationMs: number): Buffer {
const samples = Math.floor((durationMs / 1000) * this.SAMPLE_RATE);
const bufferSize = samples * this.CHANNELS * this.BYTES_PER_SAMPLE;
return Buffer.alloc(bufferSize);
}
SAMPLE_RATE = 48000;
CHANNELS = 2;
BYTES_PER_SAMPLE = 2;
FRAME_SIZE = 960;
const audioStream = this.connection.receiver.subscribe(userId, {
end: { behavior: EndBehaviorType.Manual }
});
const fileStream = createWriteStream(tempPcmFile);
const opusDecoder = new prism.opus.Decoder({
frameSize: this.FRAME_SIZE,
channels: this.CHANNELS,
rate: this.SAMPLE_RATE
});
const decodedStream = audioStream.pipe(opusDecoder);
let loggedFirstAudio = false;
decodedStream.on('data', (pcmData: Buffer) => {
const currentTime = Date.now();
const timeSinceLastAudio = currentTime - recording.lastProcessedTime;
recording.lastProcessedTime = currentTime;
// fill the gap from last time spoken by the user
if (timeSinceLastAudio > 50) {
const silenceBuffer = this.createSilenceBuffer(timeSinceLastAudio);
fileStream.write(silenceBuffer);
}
if (this.paused) {
const silenceChunk = Buffer.alloc(pcmData.length);
fileStream.write(silenceChunk);
} else {
recording.hasReceivedAudio = true;
fileStream.write(pcmData);
}
});
private createSilenceBuffer(durationMs: number): Buffer {
const samples = Math.floor((durationMs / 1000) * this.SAMPLE_RATE);
const bufferSize = samples * this.CHANNELS * this.BYTES_PER_SAMPLE;
return Buffer.alloc(bufferSize);
}