๐ฆ Supernal TTS Examples
Click to copy this entire guide to your clipboard, then paste it into your LLM conversation to give it complete instructions for integrating Supernal TTS.
Development Examples
These examples are based on the current development version of Supernal TTS. Code samples and API endpoints may change as the project evolves. Always refer to the latest documentation.
This section provides practical examples for integrating Supernal TTS into various applications and use cases.
๐ Basic Examplesโ
Simple Text-to-Speechโ
// Basic usage with mock provider (no API key needed)
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: "Hello, this is a test of Supernal TTS!",
options: { provider: 'mock' }
})
});
const data = await response.json();
console.log('Audio URL:', data.audioUrl);
// Play the audio
const audio = new Audio(data.audioUrl);
audio.play();
With Real Providerโ
// Using OpenAI provider with custom voice
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: "Welcome to our premium audio experience!",
options: {
provider: 'openai',
voice: 'fable',
speed: 1.1,
quality: 'high'
}
})
});
const data = await response.json();
console.log('Generated audio:', data);
๐ Web Integration Examplesโ
React Componentโ
import React, { useState, useRef } from 'react';
const TTSComponent = () => {
const [isLoading, setIsLoading] = useState(false);
const [audioUrl, setAudioUrl] = useState(null);
const audioRef = useRef(null);
const generateAudio = async (text) => {
setIsLoading(true);
try {
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
options: {
provider: 'openai',
voice: 'nova'
}
})
});
const data = await response.json();
setAudioUrl(data.audioUrl);
} catch (error) {
console.error('TTS Error:', error);
} finally {
setIsLoading(false);
}
};
const playAudio = () => {
if (audioRef.current) {
audioRef.current.play();
}
};
return (
<div className="tts-component">
<textarea
placeholder="Enter text to convert to speech..."
onBlur={(e) => generateAudio(e.target.value)}
/>
{isLoading && <div>Generating audio...</div>}
{audioUrl && (
<div>
<audio ref={audioRef} src={audioUrl} controls />
<button onClick={playAudio}>Play Audio</button>
</div>
)}
</div>
);
};
export default TTSComponent;
Vue.js Componentโ
<template>
<div class="tts-component">
<textarea
v-model="text"
placeholder="Enter text to convert..."
@blur="generateAudio"
/>
<div v-if="loading">Generating audio...</div>
<div v-if="audioUrl" class="audio-controls">
<audio :src="audioUrl" controls ref="audioPlayer" />
<button @click="playAudio">Play</button>
<button @click="downloadAudio">Download</button>
</div>
</div>
</template>
<script>
export default {
name: 'TTSComponent',
data() {
return {
text: '',
loading: false,
audioUrl: null
};
},
methods: {
async generateAudio() {
if (!this.text.trim()) return;
this.loading = true;
try {
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: this.text,
options: {
provider: 'cartesia',
voice: 'confident-british-man',
speed: 1.0
}
})
});
const data = await response.json();
this.audioUrl = data.audioUrl;
} catch (error) {
console.error('TTS Error:', error);
} finally {
this.loading = false;
}
},
playAudio() {
this.$refs.audioPlayer.play();
},
downloadAudio() {
const link = document.createElement('a');
link.href = this.audioUrl;
link.download = 'audio.mp3';
link.click();
}
}
};
</script>
๐ฑ Mobile App Examplesโ
React Nativeโ
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import { Audio } from 'expo-av';
const TTSScreen = () => {
const [text, setText] = useState('');
const [sound, setSound] = useState(null);
const [loading, setLoading] = useState(false);
const generateAndPlayAudio = async () => {
if (!text.trim()) return;
setLoading(true);
try {
// Generate audio
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
options: {
provider: 'openai',
voice: 'alloy',
format: 'mp3'
}
})
});
const data = await response.json();
// Play audio
const { sound: audioSound } = await Audio.Sound.createAsync(
{ uri: data.audioUrl }
);
setSound(audioSound);
await audioSound.playAsync();
} catch (error) {
Alert.alert('Error', 'Failed to generate audio');
console.error('TTS Error:', error);
} finally {
setLoading(false);
}
};
return (
<View style={{ padding: 20 }}>
<TextInput
value={text}
onChangeText={setText}
placeholder="Enter text to convert to speech..."
multiline
style={{
borderWidth: 1,
borderColor: '#ccc',
padding: 10,
marginBottom: 20,
minHeight: 100
}}
/>
<TouchableOpacity
onPress={generateAndPlayAudio}
disabled={loading}
style={{
backgroundColor: loading ? '#ccc' : '#007AFF',
padding: 15,
borderRadius: 5,
alignItems: 'center'
}}
>
<Text style={{ color: 'white' }}>
{loading ? 'Generating...' : 'Generate & Play'}
</Text>
</TouchableOpacity>
</View>
);
};
export default TTSScreen;
๐ฅ๏ธ Desktop App Examplesโ
Electron Appโ
// main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.loadFile('index.html');
}
// Handle TTS generation
ipcMain.handle('generate-tts', async (event, text, options) => {
try {
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, options })
});
const data = await response.json();
// Download audio file locally
const audioResponse = await fetch(data.audioUrl);
const audioBuffer = await audioResponse.buffer();
const audioPath = path.join(__dirname, 'temp', `${data.hash}.mp3`);
fs.writeFileSync(audioPath, audioBuffer);
return { ...data, localPath: audioPath };
} catch (error) {
throw new Error(`TTS Generation failed: ${error.message}`);
}
});
app.whenReady().then(createWindow);
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>TTS Desktop App</title>
</head>
<body>
<div>
<textarea id="textInput" placeholder="Enter text..."></textarea>
<button id="generateBtn">Generate Speech</button>
<audio id="audioPlayer" controls style="display: none;"></audio>
</div>
<script>
const { ipcRenderer } = require('electron');
document.getElementById('generateBtn').addEventListener('click', async () => {
const text = document.getElementById('textInput').value;
const audioPlayer = document.getElementById('audioPlayer');
try {
const result = await ipcRenderer.invoke('generate-tts', text, {
provider: 'openai',
voice: 'fable'
});
audioPlayer.src = result.localPath;
audioPlayer.style.display = 'block';
audioPlayer.play();
} catch (error) {
alert('Error: ' + error.message);
}
});
</script>
</body>
</html>
๐ค Bot Integration Examplesโ
Discord Botโ
const { Client, GatewayIntentBits } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
const fetch = require('node-fetch');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates]
});
client.on('messageCreate', async (message) => {
if (message.content.startsWith('!tts ')) {
const text = message.content.slice(5);
try {
// Generate audio
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
options: {
provider: 'cartesia', // Low latency for real-time
voice: 'confident-british-man'
}
})
});
const data = await response.json();
// Join voice channel and play
const voiceChannel = message.member.voice.channel;
if (voiceChannel) {
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource(data.audioUrl);
player.play(resource);
connection.subscribe(player);
}
} catch (error) {
message.reply('Sorry, I couldn\'t generate that audio.');
}
}
});
client.login('YOUR_BOT_TOKEN');
Slack Botโ
const { App } = require('@slack/bolt');
const fetch = require('node-fetch');
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
app.command('/tts', async ({ command, ack, respond }) => {
await ack();
const text = command.text;
if (!text) {
await respond('Please provide text to convert to speech.');
return;
}
try {
const response = await fetch('https://tts.supernal.ai/api/v1/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
options: {
provider: 'openai',
voice: 'nova'
}
})
});
const data = await response.json();
await respond({
text: `๐๏ธ Generated audio for: "${text}"`,
attachments: [{
fallback: 'Audio file',
title: 'Click to play audio',
title_link: data.audioUrl,
color: 'good'
}]
});
} catch (error) {
await respond('Sorry, I couldn\'t generate that audio.');
}
});
(async () => {
await app.start(process.env.PORT || 3000);
console.log('โก๏ธ Slack TTS bot is running!');
})();
๐ Educational Examplesโ
E-Learning Platformโ
class LessonPlayer {
constructor(apiUrl) {
this.apiUrl = apiUrl;
this.currentLesson = null;
this.audioCache = new Map();
}
async loadLesson(lessonId) {
const lesson = await this.fetchLesson(lessonId);
this.currentLesson = lesson;
// Pre-generate audio for all lesson segments
await this.preGenerateAudio(lesson.segments);
}
async preGenerateAudio(segments) {
const promises = segments.map(async (segment) => {
if (this.audioCache.has(segment.id)) return;
try {
const response = await fetch(`${this.apiUrl}/api/v1/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: segment.content,
options: {
provider: 'openai',
voice: 'fable',
speed: 0.9 // Slightly slower for learning
}
})
});
const data = await response.json();
this.audioCache.set(segment.id, data.audioUrl);
} catch (error) {
console.error(`Failed to generate audio for segment ${segment.id}`);
}
});
await Promise.all(promises);
}
async playSegment(segmentId) {
const audioUrl = this.audioCache.get(segmentId);
if (!audioUrl) {
throw new Error('Audio not available for this segment');
}
const audio = new Audio(audioUrl);
return new Promise((resolve) => {
audio.onended = resolve;
audio.play();
});
}
async playFullLesson() {
for (const segment of this.currentLesson.segments) {
await this.playSegment(segment.id);
// Pause between segments
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
// Usage
const player = new LessonPlayer('https://tts.supernal.ai');
await player.loadLesson('lesson-123');
await player.playFullLesson();