Skip to content

Commit

Permalink
fix: audio convertion with stream
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidsonGomes committed Jun 10, 2024
1 parent c1cbc0d commit 9cd5083
Showing 1 changed file with 22 additions and 18 deletions.
40 changes: 22 additions & 18 deletions src/api/services/channels/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2362,11 +2362,7 @@ export class BaileysStartupService extends ChannelStartupService {
});
}

public async processAudio(audio: string, number: string): Promise<string> {
number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`;
const outputAudio = `${join(this.storePath, 'temp', `${hash}.ogg`)}`;

public async processAudio(audio: string): Promise<Buffer> {
let inputAudioStream: PassThrough;

if (isURL(audio)) {
Expand All @@ -2386,23 +2382,33 @@ export class BaileysStartupService extends ChannelStartupService {
}

return new Promise((resolve, reject) => {
const outputAudioStream = new PassThrough();
const chunks: Buffer[] = [];

outputAudioStream.on('data', (chunk) => chunks.push(chunk));
outputAudioStream.on('end', () => {
const outputBuffer = Buffer.concat(chunks);
resolve(outputBuffer);
});

outputAudioStream.on('error', (error) => {
console.log('error', error);
reject(error);
});

ffmpeg.setFfmpegPath(ffmpegPath.path);

ffmpeg(inputAudioStream)
.outputFormat('ogg')
.noVideo()
.audioCodec('libopus')
.saveToFile(outputAudio)
.addOutputOptions('-avoid_negative_ts make_zero')
.audioChannels(1)
.pipe(outputAudioStream, { end: true })
.on('error', function (error) {
console.log('error', error);
reject(error);
})
.on('end', function () {
resolve(outputAudio);
})
.run();
});
});
}

Expand All @@ -2412,25 +2418,23 @@ export class BaileysStartupService extends ChannelStartupService {
}

if (data?.encoding) {
const convert = await this.processAudio(data.audio, data.number);
if (typeof convert === 'string') {
const audio = fs.readFileSync(convert).toString('base64');
const convert = await this.processAudio(data.audio);

if (Buffer.isBuffer(convert)) {
const result = this.sendMessageWithTyping<AnyMessageContent>(
data.number,
{
audio: Buffer.from(audio, 'base64'),
audio: convert,
ptt: true,
mimetype: 'audio/ogg; codecs=opus',
},
{ presence: 'recording', delay: data?.delay },
isIntegration,
);

fs.unlinkSync(convert);

return result;
} else {
throw new InternalServerErrorException(convert);
throw new InternalServerErrorException('Failed to convert audio');
}
}

Expand Down

0 comments on commit 9cd5083

Please sign in to comment.