@5minds/node-red-dashboard-2-processcube-audio-capture
Version:
A node to capture audio and pass the audio data on in the flow
69 lines (57 loc) • 2.29 kB
JavaScript
const fs = require('fs');
const tmp = require('tmp');
module.exports = function (RED) {
function AudioCaptureNode(config) {
RED.nodes.createNode(this, config);
const node = this;
const group = RED.nodes.getNode(config.group);
function addConnectionCredentials(RED, msg, conn) {
if (!msg._client) {
msg._client = {};
}
RED.plugins.getByType('node-red-dashboard-2').forEach((plugin) => {
if (plugin.hooks?.onAddConnectionCredentials && msg) {
msg = plugin.hooks.onAddConnectionCredentials(conn, msg);
}
});
msg._client = {
...msg._client,
...{
socketId: conn.id,
socketIp: conn.handshake?.address,
},
};
return msg;
}
const evts = {
onSocket: {
'handle-audio': async function (conn, id, audioData) {
let msg = {};
msg.payload = audioData;
const audioBlob = Buffer.from(audioData.fileBase64, 'base64');
try {
const tempFile = tmp.fileSync({ prefix: 'audio-', postfix: '.webm' });
fs.writeFile(tempFile.name, audioBlob, (err) => {
if (err) {
node.error('Error saving audio file:', err);
} else {
node.log(`Audio file saved to: ${tempFile.name}`);
msg.payload.filePath = tempFile.name;
msg = addConnectionCredentials(RED, msg, conn);
node.send(msg);
}
});
} catch (err) {
node.error('Error creating temporary file:', err);
}
},
},
};
if (group) {
group.register(node, config, evts);
} else {
node.error('No group configured');
}
}
RED.nodes.registerType('ui-audio-capture', AudioCaptureNode);
};