s3-aiTextToSpeech

galleryApi
Kar 2024-11-11 12:23:07 +05:30
parent 2cbf1ebbaa
commit 5e23f73645
1 changed files with 52 additions and 6 deletions

View File

@ -7,7 +7,8 @@ const aiTextToSpeech = async (req, res) => {
});
const polly = new AWS.Polly();
const s3 = new AWS.S3();
const BUCKET_NAME = 'polly-bs';
const voiceIdMap = {
"Ava": "Ivy",
"Monstero": "Justin",
@ -18,7 +19,7 @@ const aiTextToSpeech = async (req, res) => {
const { text, voiceId: frontendVoiceId } = req.body;
if (!text || !frontendVoiceId) {
if (!text || !frontendVoiceId) {
return res.status(400).json({ error: 'Text and voiceId are required' });
}
@ -30,22 +31,67 @@ const aiTextToSpeech = async (req, res) => {
const params = {
Text: text,
OutputFormat: 'mp3',
Engine:'neural',
VoiceId: pollyVoiceId,
};
try {
function generateTimestampWithRandomDigits() {
// Get the current date and time
const now = new Date();
// Format the current date as YYYY-MM-DD_HH-mm-ss
const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
// Generate 4 random digits
const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
// Concatenate the formatted date with the random digits
return `${formattedDate}_${randomDigits}`;
}
// Example usage
const folder = generateTimestampWithRandomDigits();
// Generate timestamp for folder structure
// const timestamp = moment().format('YYYY-MM-DD_HH-mm-ss');
const folderName = `audio_files/${folder}`;
// Request Polly to synthesize speech
const data = await polly.synthesizeSpeech(params).promise();
const audioBuffer = data.AudioStream;
// Define S3 paths
const audioFilePath = `${folderName}/speech.mp3`;
const textFilePath = `${folderName}/text.txt`;
// Upload audio file to S3
await s3.upload({
Bucket: BUCKET_NAME,
Key: audioFilePath,
Body: audioBuffer,
ContentType: 'audio/mpeg'
}).promise();
// Upload text file to S3
await s3.upload({
Bucket: BUCKET_NAME,
Key: textFilePath,
Body: text,
ContentType: 'text/plain'
}).promise();
// Return success response with S3 paths
res.json({
audioContent: audioBuffer.toString('base64'),
message: 'Speech generated and saved to S3 successfully',
audioFileUrl: `https://${BUCKET_NAME}.s3.amazonaws.com/${audioFilePath}`,
textFileUrl: `https://${BUCKET_NAME}.s3.amazonaws.com/${textFilePath}`
});
} catch (error) {
console.error('Error generating speech:', error);
res.status(500).json({ error: 'Error generating speech' });
console.error('Error generating speech or saving to S3:', error);
res.status(500).json({ error: 'Error generating speech or saving to S3' });
}
}
module.exports = aiTextToSpeech;