Skip to content

Commit

Permalink
fix: audio convertion with stream to mp4
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidsonGomes committed Jun 10, 2024
1 parent 9cd5083 commit 6d6f729
Showing 1 changed file with 40 additions and 35 deletions.
75 changes: 40 additions & 35 deletions src/api/services/channels/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import makeWASocket, {
import { Label } from '@whiskeysockets/baileys/lib/Types/Label';
import { LabelAssociation } from '@whiskeysockets/baileys/lib/Types/LabelAssociation';
import axios from 'axios';
import { exec } from 'child_process';
import { isBase64, isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
// import { exec } from 'child_process';
Expand Down Expand Up @@ -2118,13 +2117,11 @@ export class BaileysStartupService extends ChannelStartupService {
}

if (status.type === 'audio') {
const convert = await this.processAudioMp4(status.content, 'status@broadcast');
if (typeof convert === 'string') {
const audio = fs.readFileSync(convert).toString('base64');

const convert = await this.processAudioMp4(status.content);
if (Buffer.isBuffer(convert)) {
const result = {
content: {
audio: Buffer.from(audio, 'base64'),
audio: convert,
ptt: true,
mimetype: 'audio/ogg; codecs=opus',
},
Expand All @@ -2133,8 +2130,6 @@ export class BaileysStartupService extends ChannelStartupService {
},
};

fs.unlinkSync(convert);

return result;
} else {
throw new InternalServerErrorException(convert);
Expand Down Expand Up @@ -2326,39 +2321,54 @@ export class BaileysStartupService extends ChannelStartupService {
);
}

public async processAudioMp4(audio: string, number: string) {
let tempAudioPath: string;
let outputAudio: string;

number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`;
public async processAudioMp4(audio: string) {
let inputAudioStream: PassThrough;

if (isURL(audio)) {
outputAudio = `${join(this.storePath, 'temp', `${hash}.mp4`)}`;
tempAudioPath = `${join(this.storePath, 'temp', `temp-${hash}.mp3`)}`;

const timestamp = new Date().getTime();
const url = `${audio}?timestamp=${timestamp}`;

const response = await axios.get(url, { responseType: 'arraybuffer' });
const config: any = {
responseType: 'stream',
};

fs.writeFileSync(tempAudioPath, response.data);
const response = await axios.get(url, config);
inputAudioStream = response.data.pipe(new PassThrough());
} else {
outputAudio = `${join(this.storePath, 'temp', `${hash}.mp4`)}`;
tempAudioPath = `${join(this.storePath, 'temp', `temp-${hash}.mp3`)}`;

const audioBuffer = Buffer.from(audio, 'base64');
fs.writeFileSync(tempAudioPath, audioBuffer);
inputAudioStream = new PassThrough();
inputAudioStream.end(audioBuffer);
}

return new Promise((resolve, reject) => {
exec(`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`, (error) => {
fs.unlinkSync(tempAudioPath);
const outputAudioStream = new PassThrough();
const chunks: Buffer[] = [];

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

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

ffmpeg.setFfmpegPath(ffmpegPath.path);

ffmpeg(inputAudioStream)
.outputFormat('mp4')
.noVideo()
.audioCodec('aac')
.audioBitrate('128k')
.audioFrequency(44100)
.addOutputOptions('-f ipod')
.pipe(outputAudioStream, { end: true })
.on('error', function (error) {
console.log('error', error);
reject(error);
});
});
}

Expand Down Expand Up @@ -2853,12 +2863,9 @@ export class BaileysStartupService extends ChannelStartupService {
const typeMessage = getContentType(msg.message);

if (convertToMp4 && typeMessage === 'audioMessage') {
const number = msg.key.remoteJid.split('@')[0];
const convert = await this.processAudioMp4(buffer.toString('base64'), number);

if (typeof convert === 'string') {
const audio = fs.readFileSync(convert).toString('base64');
const convert = await this.processAudioMp4(buffer.toString('base64'));

if (Buffer.isBuffer(convert)) {
const result = {
mediaType,
fileName: mediaMessage['fileName'],
Expand All @@ -2869,11 +2876,9 @@ export class BaileysStartupService extends ChannelStartupService {
width: mediaMessage['width'],
},
mimetype: 'audio/mp4',
base64: Buffer.from(audio, 'base64').toString('base64'),
base64: convert,
};

fs.unlinkSync(convert);

return result;
}
}
Expand Down

0 comments on commit 6d6f729

Please sign in to comment.