Node.js TTS Entegrasyonu: Tam Rehber
Node.js, TTS entegrasyonları için en yaygın runtime. İşte doğru inşa etmenin yolu.
Kurulum
npm install @speeko/sdkTemel İstek
import { Speeko } from '@speeko/sdk';
const client = new Speeko({ apiKey: process.env.SPEEKO_KEY });
const audio = await client.tts({
text: 'Merhaba dünya',
voice: 'tr_female_aylin',
format: 'mp3'
});
await fs.promises.writeFile('output.mp3', audio);Express Entegrasyonu
import express from 'express';
import { Speeko } from '@speeko/sdk';
const app = express();
const speeko = new Speeko({ apiKey: process.env.SPEEKO_KEY });
app.use(express.json());
app.post('/api/tts', async (req, res) => {
try {
const { text, voice = 'tr_female_aylin' } = req.body;
if (!text || text.length > 5000) {
return res.status(400).json({ error: 'Geçersiz metin' });
}
const audio = await speeko.tts({ text, voice });
res.set('Content-Type', 'audio/mpeg');
res.set('Cache-Control', 'public, max-age=31536000');
res.send(audio);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000);İstemciye Streaming
TTS çıktısını doğrudan tarayıcıya pipe'layın:
app.get('/api/tts/stream', async (req, res) => {
const { text } = req.query;
res.set({
'Content-Type': 'audio/mpeg',
'Transfer-Encoding': 'chunked'
});
const stream = speeko.ttsStream({ text, voice: 'tr_female_aylin' });
stream.on('data', chunk => res.write(chunk));
stream.on('end', () => res.end());
stream.on('error', err => {
console.error(err);
res.destroy();
});
});İstemci Tarafı Oynatma
<audio controls>
<source src="/api/tts/stream?text=Merhaba" type="audio/mpeg">
</audio>Fastify (Daha Yüksek Performans)
import fastify from 'fastify';
import { Speeko } from '@speeko/sdk';
const app = fastify();
const speeko = new Speeko({ apiKey: process.env.SPEEKO_KEY });
app.post('/tts', {
schema: {
body: {
type: 'object',
required: ['text'],
properties: {
text: { type: 'string', maxLength: 5000 },
voice: { type: 'string' }
}
}
}
}, async (req, reply) => {
const audio = await speeko.tts(req.body);
reply.type('audio/mpeg').send(audio);
});
app.listen({ port: 3000 });Hata Yönetimi
try {
const audio = await speeko.tts({ text, voice });
} catch (err) {
if (err.code === 'rate_limit_exceeded') {
await sleep(err.retryAfter * 1000);
} else if (err.code === 'insufficient_credits') {
notifyBilling();
} else {
throw err;
}
}Üretim Kontrol Listesi
- API anahtarları için ortam değişkenleri kullanın
- İstek zaman aşımını etkinleştirin (30sn varsayılan iyi)
- Debug için request ID'leri loglayın
- Yaygın ifadeleri önbelleğe alın (önbellekleme makalemize bakın)
- Yapılandırılmış loglama kurun (pino önerilir)
- Saatlik TTS çağıran sağlık kontrol endpoint'i