UNPKG

react-native-gtts-lite

Version:

🎙️ Lightweight Google Translate TTS for React Native CLI using react-native-fs and react-native-sound.

45 lines (37 loc) 1.11 kB
const Sound = require('react-native-sound'); const RNFS = require('react-native-fs'); const BASE_URL = 'https://translate.google.com/translate_tts'; async function speak(text, lang = 'en') { try { const url = `${BASE_URL}?ie=UTF-8&q=${encodeURIComponent(text)}&tl=${lang}&client=tw-ob`; const tempPath = `${RNFS.CachesDirectoryPath}/gtts_${Date.now()}.mp3`; const download = await RNFS.downloadFile({ fromUrl: url, toFile: tempPath, headers: { 'User-Agent': 'Mozilla/5.0', }, }).promise; if (download.statusCode !== 200) { console.error('Failed to download audio. Status code:', download.statusCode); return; } const sound = new Sound(tempPath, '', (error) => { if (error) { console.error('Error loading sound:', error); return; } sound.play((success) => { if (!success) { console.error('Sound playback failed'); } sound.release(); // Clean up }); }); } catch (err) { console.error('Error in speak():', err); } } module.exports = { speak, };