FantasyTalking User Manual
Basic Features
FantasyTalking provides comprehensive speech synthesis and dialogue functions. This manual will introduce how to use various features in detail.
Speech Synthesis
Speech synthesis is FantasyTalking's core feature, converting text into natural and smooth speech. Here is the basic usage:
// Simple text-to-speech
const audio = await client.speak('Hello, welcome to FantasyTalking');
// Specify voice style
const audio = await client.speak('The weather is great today', {
voice: {
style: 'happy',
language: 'en-US'
}
});
// Specify speed and pitch
const audio = await client.speak('Please wait a moment', {
voice: {
speed: 1.2,
pitch: 0.9
}
});
SSML Markup Language
FantasyTalking supports SSML markup language for finer control over speech output:
<speak>
<p>
<s>First sentence.</s>
<s>Second sentence.</s>
</p>
<break time="500ms"/>
<p>
<emphasis level="moderate">This is important content</emphasis>
</p>
</speak>
Corresponding JavaScript code:
const ssml = `
<speak>
<p>
<s>First sentence.</s>
<s>Second sentence.</s>
</p>
<break time="500ms"/>
<p>
<emphasis level="moderate">This is important content</emphasis>
</p>
</speak>
`;
const audio = await client.speak(ssml, { ssml: true });
Voice Events
During speech playback, you can listen to various events for interaction:
// Listen for speech start
client.on('speech-start', (event) => {
console.log('Speech started playing');
});
// Listen for word boundary (for subtitle sync)
client.on('word-boundary', (event) => {
console.log(`Current word: ${event.word}`);
console.log(`Start time: ${event.start}ms`);
console.log(`End time: ${event.end}ms`);
});
// Listen for speech end
client.on('speech-end', (event) => {
console.log('Speech playback completed');
});
// Listen for errors
client.on('error', (event) => {
console.error('Error:', event.error);
});
Batch Synthesis
When needing to synthesize large amounts of text, you can use batch synthesis for better efficiency:
const texts = [
'This is the first voice',
'This is the second voice',
'This is the third voice'
];
// Parallel synthesis
const results = await Promise.all(
texts.map(text => client.speak(text))
);
// Sequential synthesis (preserving order)
const results = [];
for (const text of texts) {
const audio = await client.speak(text);
results.push(audio);
}
Dialogue Features
Basic Dialogue
FantasyTalking provides powerful dialogue management functions, supporting multi-turn conversations and context memory:
// Create dialogue session
const session = client.createSession({
// Optional: set system prompt
systemPrompt: 'You are a friendly assistant, good at answering questions',
// Optional: set language
language: 'en-US'
});
// First turn
const response1 = await session.chat('How is the weather today?');
console.log(response1.text); // AI response text
console.log(response1.audio); // AI response audio
// Second turn (automatically includes context)
const response2 = await session.chat('What about tomorrow?');
console.log(response2.text);
Dialogue Configuration
You can configure for different dialogue scenarios:
const session = client.createSession({
// Dialogue configuration
dialogue: {
// Temperature, controls response creativity
temperature: 0.7,
// Max response tokens
maxTokens: 500,
// Topic tags, for distinguishing scenarios
tags: ['customer-service', 'pre-sales']
},
// Voice configuration
voice: {
// AI response voice style
style: 'professional',
// Speech rate
speed: 1.0
}
});
Dialogue History Management
// Get dialogue history
const history = session.getHistory();
console.log(history);
// Save dialogue history
const savedHistory = session.save();
fs.writeFileSync('conversation.json', JSON.stringify(savedHistory));
// Load dialogue history
const loadedSession = client.loadSession(savedHistory);
Advanced Features
Streaming Speech Synthesis
For real-time feedback scenarios, you can use streaming speech synthesis:
// Enable streaming output
const stream = await client.speakStream('This is a long piece of text');
// Listen for data chunks
stream.on('data', (chunk) => {
// Play audio chunk
audioPlayer.play(chunk);
});
stream.on('end', () => {
console.log('Speech synthesis completed');
});
stream.on('error', (error) => {
console.error('Error:', error);
});
Custom Voice Models
If you need a brand-exclusive voice, you can train custom models:
// Prepare training data
const trainingData = {
name: 'Brand Voice',
description: 'Voice for enterprise brand',
samples: [
{ text: 'Sample text 1', audio: 'base64 encoded audio 1' },
{ text: 'Sample text 2', audio: 'base64 encoded audio 2' },
// More samples...
]
};
// Submit training job
const job = await client.trainVoice(trainingData);
// Poll training status
while (job.status !== 'completed') {
await sleep(5000);
const status = await client.getJobStatus(job.id);
console.log(`Training progress: ${status.progress}%`);
}
// After training, use custom voice
const audio = await client.speak('Using custom voice', {
voice: {
modelId: job.modelId
}
});
Audio Post-Processing
FantasyTalking provides various audio post-processing functions:
const audio = await client.speak('Original speech');
// Volume adjustment
const normalized = client.process(audio, {
normalize: true,
targetLevel: -20 // dB
});
// Noise reduction
const denoised = client.process(audio, {
denoise: true,
noiseThreshold: 0.5
});
// Speed adjustment
const spedUp = client.process(audio, {
speed: 1.5 // 1.5x speed
});
Best Practices
Performance Optimization
In real applications, pay attention to the following for performance optimization:
- Connection reuse: Avoid frequently creating client instances; reusing connections can significantly reduce latency
- Batch processing: When processing large amounts of text, use batch synthesis
- Caching: For identical text, use caching to avoid duplicate synthesis
- Streaming output: Use streaming output for long text to start playback earlier and improve user experience
Error Handling
It is recommended to implement comprehensive error handling:
try {
const audio = await client.speak('Test text');
} catch (error) {
if (error.code === 'RATE_LIMIT') {
// Handle rate limit
console.log('Too many requests, please try again later');
} else if (error.code === 'INVALID_API_KEY') {
// Handle authentication error
console.log('Invalid API key');
} else {
// Other errors
console.error('Unknown error:', error);
}
}
User Experience
For better user experience, it is recommended to:
- Pre-loading: Pre-synthesize speech before users might need it
- Feedback: Provide visual feedback during speech playback
- Interruption handling: Support user interrupting speech playback
- Offline support: Implement offline support for basic features
