#save audio to file
1 messages · Page 1 of 1 (latest)
voice messages
client.on('message', async msg => {
if(msg.hasMedia){
const media = await msg.downloadMedia();
var mediaType = media.mimetype;
if(mediaType.indexOf("audio/ogg") >= 0){
var media_filename = "export-voice.ogg";
var media_source = "data:"+media.mimetype+";base64,"+media.data;
media_source = media_source.replace('data:audio/ogg; codecs=opus;base64,', '');
media_source = media_source.replace(/ /g, '+');
var media_base64 = Buffer.from(media_source, 'base64');
files.writeFileSync("/path/to/files/"+media_filename, media_base64);
}
}
});
This simple code checks whether the received message contains media and if the type is audio/ogg (which is the type used by voice messages) proceeds to save the file in the directory selected by you.
Cannot read properties of undefined (reading 'mimetype')
const media = await msg.downloadMedia();
var mediaType = media.mimetype;
if (msg.hasMedia) {
const quotedMsg = await msg.getQuotedMessage();
const media = await quotedMsg.downloadMedia();
var mediaType = media.mimetype;
if (mediaType.indexOf("audio/ogg") >= 0) {
var media_filename = "export-voice.ogg";
var media_source = "data:" + media.mimetype + ";base64," + media.data;
media_source = media_source.replace('data:audio/ogg; codecs=opus;base64,', '');
media_source = media_source.replace(/ /g, '+');
var media_base64 = Buffer.from(media_source, 'base64');
files.writeFileSync("/path/to/files/" + media_filename, media_base64);
}
}
if (message.type === 'ptt') {
const msg_from = message.from.substring(0, 6);
(async () => {
var media = await message.downloadMedia();
var audioFile11 = "./audios/" + Math.floor(Math.random() * 99999) + ".ptt";
fs.writeFile(
audioFile11,
media.data,
"base64",
function (err) {
if (err) {
console.log(err);
}
}
);
}
Cannot read properties of undefined (reading 'data')
Did you define messagemedia at the beginning of your project?
const { MessageMedia } = require('whatsapp-web.js');
You can also define the Client in the same line for cleaner code
const { Client, MessageMedia } = require('whatsapp-web.js');
already imported
What kind of media are your receiving??
voice message
I've been trying since yesterday and I still can't get it, it can't be