#I cant send Audio files

20 messages · Page 1 of 1 (latest)

frank light
#

Hello friends, I have this code to send audio recordings to S3, save the message in the database, and then send it to WhatsApp. However, I can't send audio files with WWebJS.

in frontend:

      navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
        this.mediaRecorder = new MediaRecorder(stream);
        this.mediaRecorder.start();
        this.isRecording = true;
        this.audioChunks = [];

        this.mediaRecorder.addEventListener("dataavailable", (event) => {
          this.audioChunks.push(event.data);
        });

        this.mediaRecorder.addEventListener("stop", async () => {
          const audioBlob = new Blob(this.audioChunks, {
            type: "audio/ogg; codecs=opus",
          });
          const formData = new FormData();
          formData.append("file", audioBlob);
          formData.append("id", this.Chats[0].chatId);
          formData.append("user", this.token.name);
          formData.append("number", this.Chats[0].phoneNumber);
          formData.append("chatId", this.id);
          formData.append("mediaType", "audio/ogg; codecs=opus");

          let response = await api.post("/api/v1/whatsapp/messages", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
              Authorization: "Bearer " + this.token.token,
            },
          });
          this.isRecording = false;
          await this.getMessages();
        });
      });
    },```
#

in backend:

  const { id, chatId, number, user, message, mediaType } = req.body;
  const file = req.file;

  try {
    let mediaUrl = null;
    let mediaKey = null;

    if (file) {
      mediaKey = `whatsapp/${id}/${uuidv4()}.${file.mimetype.split('/')[1]}`;
      const params = {
        Bucket: process.env.AWS_BUCKET_NAME,
        Key: mediaKey,
        Body: file.buffer,
        ContentType: file.mimetype,
      };

      await s3.upload(params).promise();
    }

    console.log("CHATID", chatId);

    const newMessage = await db.messageWhatsApp.create({
      data: {
        chatId: chatId,
        message: message || '',
        mediaUrl: mediaKey,
        mediaType: mediaType || null,
        read: false,
        isClient: false,
      },
    });

    let formattedMessage = `[${user}] ${message}`;
    console.log(`Enviando mensagem: ${id}, ${formattedMessage}`);

    if (file) {
      formattedMessage = `[${user}]`;
      // Obter a URL assinada do S3
      const params = {
        Bucket: process.env.AWS_BUCKET_NAME,
        Key: mediaKey,
        Expires: 60 * 60 // URL válida por 1 hora
      };

      mediaUrl = s3.getSignedUrl('getObject', params);

      if (mediaType.includes('image')) {
        const response = await axios.get(mediaUrl, {
          responseType: 'arraybuffer'
        });

        const base64Image = Buffer.from(response.data, 'binary').toString('base64');
        const media = new MessageMedia('image/png', base64Image);
        await client.sendMessage(id, media, { caption: formattedMessage });

      }````
#
        const response = await axios.get(mediaUrl, {
          responseType: 'arraybuffer'
        });
      
        const audioBuffer = Buffer.from(response.data, 'binary');
        const media = new MessageMedia('audio/ogg; codecs=opus', audioBuffer.toString('base64'), 'audio.ogg');
        console.log("MIDIA", media);
        await client.sendMessage(id, media, { sendAudioAsVoice: true, caption: formattedMessage });
      }
    } else {
      await client.sendMessage(id, formattedMessage);
    }
    // Enviar a resposta HTTP após todas as operações assíncronas
    res.json(newMessage);
  } catch (err) {
    console.log(err);
    return res.status(500).json({ error: err });
  }
});```

  give this error:

```Error: Evaluation failed: a
    at ExecutionContext._ExecutionContext_evaluate (/home/lokize/Developer/DevOps/backend/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.js:229:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ExecutionContext.evaluate (/home/lokize/Developer/DevOps/backend/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.js:107:16)
    at async Client.sendMessage (/home/lokize/Developer/DevOps/backend/node_modules/whatsapp-web.js/src/Client.js:950:28)
    at async 
/home/lokize/Developer/DevOps/backend/src/api/whatsapp/whatsapp.routes.js:184:9
POST /backend/api/v1/whatsapp/messages 500 790.219 ms - 12```
#

for some reason I can't send the audio file, the images work normally.

lunar coral
#

1- Check the real codec of the audio file;
2- Are you using Chromium or Chrome, it's better use Chrome.

frank light
#

executablePath: "/usr/bin/google-chrome-stable",

#

seems a real ogg file

#

but maybe conversion is not good, dont work with wav file?

lunar coral
#

.mp3: audio/mpeg
.ogg: audio/ogg; codecs=opus

#

Post the file here

frank light
lunar coral
#

The file is in wrong format

frank light
#

Thank you for the help. I'll try to convert the file to the correct format before uploading it to S3

#

"I converted it, but a similar error still occurs when trying to send it on WhatsApp.

lunar coral
frank light
#

sorry i converted to correct format now and its working good

lunar coral
#

Alright