react-native-gtts-lite
Version:
🎙️ Lightweight Google Translate TTS for React Native CLI using react-native-fs and react-native-sound.
63 lines (51 loc) • 1.65 kB
JavaScript
const Sound = require('react-native-sound');
const RNFS = require('react-native-fs');
const { Platform } = require('react-native');
const BASE_URL = 'https://translate.google.com/translate_tts';
async function speak(text, lang = 'en', options = {}) {
try {
const { save = false, fileName = `tts_output_${Date.now()}.mp3` } = options;
const query = `${BASE_URL}?ie=UTF-8&client=tw-ob&tl=${lang}&q=${encodeURIComponent(text)}`;
const tempPath = `${RNFS.CachesDirectoryPath}/gtts_${Date.now()}.mp3`;
const download = await RNFS.downloadFile({
fromUrl: query,
toFile: tempPath,
headers: {
'User-Agent': 'Mozilla/5.0', // Required to prevent 403
},
}).promise;
if (download.statusCode !== 200) {
console.error('TTS download failed:', download.statusCode);
return;
}
let finalPath = tempPath;
// If user wants to save the file permanently
if (save) {
const dir =
Platform.OS === 'android'
? RNFS.DownloadDirectoryPath
: RNFS.DocumentDirectoryPath;
finalPath = `${dir}/${fileName}`;
await RNFS.copyFile(tempPath, finalPath);
console.log(`Audio saved to: ${finalPath}`);
}
// Play the audio
const sound = new Sound(finalPath, '', (error) => {
if (error) {
console.error('Sound load error:', error);
return;
}
sound.play((success) => {
if (!success) {
console.error('Playback failed');
}
sound.release(); // Clean up
});
});
} catch (err) {
console.error('TTS error:', err);
}
}
module.exports = {
speak,
};