From 81efa2e8eb0549250e57364c976860054923da4e Mon Sep 17 00:00:00 2001 From: Hamza-Ayed Date: Fri, 22 May 2026 19:53:15 +0300 Subject: [PATCH] Add FFmpeg MP3 to OGG Opus conversion for native voice notes --- whatsapp-gateway/baileys-client.js | 49 +++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/whatsapp-gateway/baileys-client.js b/whatsapp-gateway/baileys-client.js index 1c71160..52f2567 100644 --- a/whatsapp-gateway/baileys-client.js +++ b/whatsapp-gateway/baileys-client.js @@ -311,6 +311,30 @@ async function disconnectSession(session_key) { } } +const { exec } = require('child_process'); +const os = require('os'); + +function convertToOggOpus(base64Audio) { + return new Promise((resolve, reject) => { + const timeId = Date.now() + Math.random().toString(36).substring(7); + const inputPath = path.join(os.tmpdir(), `input_${timeId}.tmp`); + const outputPath = path.join(os.tmpdir(), `output_${timeId}.ogg`); + + fs.writeFile(inputPath, Buffer.from(base64Audio, 'base64'), (err) => { + if (err) return reject(err); + exec(`ffmpeg -i ${inputPath} -c:a libopus -y ${outputPath}`, (execErr) => { + fs.unlink(inputPath, () => {}); + if (execErr) return reject(execErr); + fs.readFile(outputPath, (readErr, data) => { + fs.unlink(outputPath, () => {}); + if (readErr) return reject(readErr); + resolve(data.toString('base64')); + }); + }); + }); + }); +} + /** * Send a message using an active session */ @@ -324,14 +348,29 @@ async function sendMessage(session_key, phone, message, mediaUrl = null, audioBa let sentMsg; if (audioBase64) { - const buffer = Buffer.from(audioBase64, 'base64'); - const mime = mimetype || 'audio/mp4'; - const isMp3 = mime.includes('mpeg') || mime.includes('mp3'); + let finalAudioBase64 = audioBase64; + let finalMime = mimetype || 'audio/mp4'; + + // If it's MP3, convert to OGG Opus to ensure iPhone PTT compatibility + if (finalMime.includes('mpeg') || finalMime.includes('mp3')) { + try { + console.log(`[Baileys] Converting MP3 to OGG Opus for native PTT...`); + finalAudioBase64 = await convertToOggOpus(audioBase64); + finalMime = 'audio/ogg; codecs=opus'; + } catch (err) { + console.error(`[Baileys] FFmpeg conversion failed:`, err.message); + // Fallback to sending as normal audio if conversion fails + finalMime = 'audio/mp4'; + } + } + + const buffer = Buffer.from(finalAudioBase64, 'base64'); + const isMp3 = finalMime.includes('mpeg') || finalMime.includes('mp3'); sentMsg = await sock.sendMessage(jid, { audio: buffer, - mimetype: mime, - ptt: !isMp3 // Disable PTT for MP3 to prevent iOS playback errors + mimetype: finalMime, + ptt: !isMp3 // PTT enabled for OGG/MP4, disabled for raw MP3 }); } else if (mediaUrl) { const ext = mediaUrl.split('.').pop().toLowerCase();