Created
July 25, 2023 01:29
-
-
Save maskaravivek/890310a5e817a78a0b5dd16a1a7ccdb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require("aws-sdk"); | |
var languageConfiguration = require("./language-configuration"); | |
const polly = new AWS.Polly({ | |
signatureVersion: "v4", | |
region: process.env.AWS_REGION, | |
}); | |
const readTextFile = (filePath) => { | |
const fs = require("fs"); | |
const text = fs.readFileSync(filePath, "utf-8"); | |
return text; | |
}; | |
const synthesize = async (localFilePath) => { | |
const text = readTextFile(localFilePath); | |
const paragraphs = text.split("\n\n"); | |
const iso2Lang = "en"; | |
const audioBuffers = []; | |
const langConfig = | |
languageConfiguration.getLangConfigurationOrDefault(iso2Lang); | |
for (const paragraph of paragraphs) { | |
const paragraphWithBreak = `${paragraph} <break strength="x-strong" />`; | |
const splittedText = chunkString(paragraphWithBreak, 1400); | |
const paragraphBuffers = await Promise.all( | |
splittedText.map((chunk) => { | |
return polly | |
.synthesizeSpeech({ | |
OutputFormat: "mp3", | |
TextType: "ssml", | |
Text: `<speak>${chunk}</speak>`, | |
LanguageCode: langConfig.langCode, | |
Engine: langConfig.engine, | |
VoiceId: langConfig.voiceId, | |
}) | |
.promise() | |
.then((data) => data.AudioStream); | |
}) | |
); | |
audioBuffers.push(...paragraphBuffers); | |
} | |
const mergedBuffers = audioBuffers.reduce( | |
(total, buffer) => | |
Buffer.concat([total, buffer], total.length + buffer.length), | |
Buffer.alloc(1) | |
); | |
return mergedBuffers; | |
}; | |
const chunkString = (paragraph, chunkSize) => { | |
let splitString = []; | |
for (let i = 0; i < paragraph.length; i = i + chunkSize) { | |
splitString.push(paragraph.slice(i, i + chunkSize)); | |
} | |
return splitString; | |
}; | |
module.exports = { | |
synthesize, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment