voirs 0.1.0-alpha.2

Advanced voice synthesis and speech processing library for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# Quick Start

This guide will get you up and running with VoiRS Text-to-Speech synthesis in just a few minutes.

## Prerequisites

Make sure you have completed the [Installation](./installation.md) guide first.

## Your First Synthesis

Let's start with a simple example to synthesize speech from text:

```rust
use voirs::prelude::*;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt::init();

    // Create the synthesis pipeline components
    let g2p = create_g2p(G2pBackend::RuleBased);
    let acoustic = create_acoustic(AcousticBackend::Vits);
    let vocoder = create_vocoder(VocoderBackend::HifiGan);

    // Build the synthesis pipeline
    let pipeline = VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .build()
        .await?;

    // Text to synthesize
    let text = "Hello, world! This is VoiRS speaking in pure Rust.";

    // Perform synthesis
    let audio = pipeline.synthesize(text).await?;

    // Save the result as a WAV file
    audio.save_wav("output.wav")?;

    println!("โœ… Synthesis completed! Audio saved to output.wav");
    println!("๐Ÿ“Š Audio info: {:.2}s duration, {} Hz sample rate",
             audio.duration(), audio.sample_rate());

    Ok(())
}
```

## Streaming Synthesis

For real-time synthesis with streaming capabilities:

```rust
use voirs::prelude::*;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    // Create pipeline with streaming configuration
    let g2p = create_g2p(G2pBackend::RuleBased);
    let acoustic = create_acoustic(AcousticBackend::Vits);
    let vocoder = create_vocoder(VocoderBackend::HifiGan);

    let pipeline = VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .with_streaming_enabled(true)
        .build()
        .await?;

    // Create streaming synthesizer
    let mut stream = pipeline.create_stream().await?;

    // Text chunks to synthesize in real-time
    let text_chunks = vec![
        "Hello there! ",
        "This is streaming ",
        "text-to-speech synthesis ",
        "powered by VoiRS. ",
        "Each chunk is processed ",
        "as soon as it arrives."
    ];

    println!("๐ŸŽค Starting streaming synthesis...");

    for (i, chunk) in text_chunks.iter().enumerate() {
        println!("Processing chunk {}: '{}'", i + 1, chunk);

        // Send text chunk for synthesis
        stream.send_text(chunk).await?;

        // Get audio output as it becomes available
        while let Some(audio_chunk) = stream.receive_audio().await? {
            let filename = format!("stream_chunk_{:02}.wav", i + 1);
            audio_chunk.save_wav(&filename)?;
            println!("  ๐Ÿ’พ Saved audio chunk: {}", filename);
        }
    }

    // Finalize the stream
    stream.finalize().await?;
    println!("โœ… Streaming synthesis completed!");

    Ok(())
}
```

## Batch Synthesis

Process multiple texts efficiently with batch synthesis:

```rust
use voirs::prelude::*;
use anyhow::Result;
use tokio::fs;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    // Create the synthesis pipeline
    let g2p = create_g2p(G2pBackend::RuleBased);
    let acoustic = create_acoustic(AcousticBackend::Vits);
    let vocoder = create_vocoder(VocoderBackend::HifiGan);

    let pipeline = VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .build()
        .await?;

    // Multiple texts to synthesize
    let texts = [
        "Welcome to VoiRS, the pure Rust speech synthesis framework.",
        "This example demonstrates batch processing capabilities.",
        "Each text is synthesized independently and saved to a separate file.",
        "VoiRS delivers high-quality, natural-sounding speech output."
    ];

    // Create output directory
    fs::create_dir_all("batch_output").await?;

    println!("๐ŸŽค Starting batch synthesis...");

    for (i, text) in texts.iter().enumerate() {
        println!("Processing text {}: {}", i + 1, text);

        // Synthesize each text
        let audio = pipeline.synthesize(text).await?;
        let output_path = format!("batch_output/output_{:02}.wav", i + 1);

        // Save the audio file
        audio.save_wav(&output_path)?;
        println!("  ๐Ÿ’พ Saved: {} ({:.2}s duration)", output_path, audio.duration());
    }

    println!("โœ… Batch synthesis completed! Check the batch_output/ directory.");

    Ok()
}
```

## SSML Support

Use Speech Synthesis Markup Language for advanced control:

```rust
use voirs::prelude::*;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    // Create pipeline with SSML support
    let g2p = create_g2p(G2pBackend::RuleBased);
    let acoustic = create_acoustic(AcousticBackend::Vits);
    let vocoder = create_vocoder(VocoderBackend::HifiGan);

    let pipeline = VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .with_ssml_enabled(true)
        .build()
        .await?;

    // SSML text with prosody control
    let ssml_text = r#"
        <speak>
            <p>
                <emphasis level="strong">Welcome</emphasis> to VoiRS!
            </p>
            <break time="1s"/>
            <p>
                This text uses <prosody rate="slow">slow speech</prosody>
                and then <prosody rate="fast">fast speech</prosody>.
            </p>
            <break time="500ms"/>
            <p>
                You can also control <prosody pitch="high">pitch</prosody>
                and <prosody volume="loud">volume</prosody>.
            </p>
        </speak>
    "#;

    println!("๐ŸŽค Synthesizing SSML content...");

    // Synthesize with SSML interpretation
    let audio = pipeline.synthesize_ssml(ssml_text).await?;

    // Save the result
    audio.save_wav("ssml_output.wav")?;

    println!("โœ… SSML synthesis completed!");
    println!("๐Ÿ“Š Generated {:.2}s of audio with prosodic controls", audio.duration());

    Ok(())
}
```

## Multi-language Support

Synthesize speech in different languages:

```rust
use voirs::prelude::*;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    // Define texts in different languages
    let languages = vec![
        (LanguageCode::EnUs, "Hello, this is English text-to-speech."),
        (LanguageCode::EsEs, "Hola, esto es sรญntesis de voz en espaรฑol."),
        (LanguageCode::JaJp, "ใ“ใ‚“ใซใกใฏใ€ใ“ใ‚Œใฏๆ—ฅๆœฌ่ชžใฎ้Ÿณๅฃฐๅˆๆˆใงใ™ใ€‚"),
        (LanguageCode::FrFr, "Bonjour, ceci est une synthรจse vocale franรงaise."),
    ];

    println!("๐ŸŒ Starting multi-language synthesis...");

    for (lang, text) in languages {
        println!("Synthesizing {:?}: {}", lang, text);

        // Create language-specific pipeline
        let g2p = create_g2p_for_language(G2pBackend::RuleBased, lang);
        let acoustic = create_acoustic_for_language(AcousticBackend::Vits, lang);
        let vocoder = create_vocoder(VocoderBackend::HifiGan);

        let pipeline = VoirsPipelineBuilder::new()
            .with_g2p(g2p)
            .with_acoustic_model(acoustic)
            .with_vocoder(vocoder)
            .with_language(lang)
            .build()
            .await?;

        // Synthesize the text
        let audio = pipeline.synthesize(text).await?;
        let output_file = format!("output_{:?}.wav", lang).to_lowercase();

        audio.save_wav(&output_file)?;
        println!("  ๐Ÿ’พ Saved: {} ({:.2}s)", output_file, audio.duration());
    }

    println!("โœ… Multi-language synthesis completed!");

    Ok(())
}
```

## Performance Optimization

Optimize synthesis performance for production use:

```rust
use voirs::prelude::*;
use anyhow::Result;
use std::time::Instant;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    // Performance monitoring setup
    let startup_start = Instant::now();

    // Create optimized pipeline with performance settings
    let g2p = create_g2p(G2pBackend::RuleBased);
    let acoustic = create_acoustic_with_config(
        AcousticBackend::Vits,
        AcousticConfig::performance_optimized()
    );
    let vocoder = create_vocoder_with_config(
        VocoderBackend::HifiGan,
        VocoderConfig::fast_inference()
    );

    let pipeline = VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .with_batch_size(8)  // Optimize for batch processing
        .with_cache_enabled(true)  // Enable model caching
        .build()
        .await?;

    let startup_time = startup_start.elapsed();
    println!("๐Ÿš€ Pipeline startup: {:?}", startup_time);

    // Test synthesis performance
    let test_text = "This is a performance test for VoiRS speech synthesis.";

    let synthesis_start = Instant::now();
    let audio = pipeline.synthesize(test_text).await?;
    let synthesis_time = synthesis_start.elapsed();

    // Calculate Real-Time Factor (RTF)
    let rtf = synthesis_time.as_secs_f32() / audio.duration();

    println!("๐Ÿ“Š Performance Metrics:");
    println!("  Synthesis time: {:?}", synthesis_time);
    println!("  Audio duration: {:.2}s", audio.duration());
    println!("  Real-time factor: {:.3}x", rtf);
    println!("  Status: {}", if rtf < 1.0 { "โœ… Real-time capable" } else { "โš ๏ธ Slower than real-time" });

    // Save performance test result
    audio.save_wav("performance_test.wav")?;

    // Batch performance test
    let batch_texts = vec![
        "First sentence for batch testing.",
        "Second sentence with different content.",
        "Third sentence to complete the batch.",
        "Fourth and final sentence in this performance test."
    ];

    println!("
๐Ÿ”„ Testing batch synthesis...");
    let batch_start = Instant::now();

    for (i, text) in batch_texts.iter().enumerate() {
        let audio = pipeline.synthesize(text).await?;
        let filename = format!("batch_perf_{:02}.wav", i + 1);
        audio.save_wav(&filename)?;
    }

    let batch_time = batch_start.elapsed();
    println!("  Batch synthesis: {:?} for {} texts", batch_time, batch_texts.len());
    println!("  Average per text: {:?}", batch_time / batch_texts.len() as u32);

    Ok(())
}
```

## Error Handling

Robust error handling for production applications:

```rust
use voirs::prelude::*;
use anyhow::{Context, Result};

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    println!("๐ŸŽค VoiRS Synthesis with Error Handling");

    // Attempt to create synthesis pipeline with detailed error handling
    let pipeline = match create_synthesis_pipeline().await {
        Ok(p) => p,
        Err(e) => {
            eprintln!("โŒ Failed to create synthesis pipeline: {}", e);
            return Err(e);
        }
    };

    let text = "This example demonstrates proper error handling in VoiRS.";

    // Attempt synthesis with comprehensive error handling
    match pipeline.synthesize(text).await {
        Ok(audio) => {
            match audio.save_wav("error_handling_output.wav") {
                Ok(_) => {
                    println!("โœ… Success: Audio synthesized and saved!");
                    println!("๐Ÿ“Š Duration: {:.2}s, Sample Rate: {}Hz",
                             audio.duration(), audio.sample_rate());
                }
                Err(e) => {
                    eprintln!("โŒ Failed to save audio file: {}", e);
                    return Err(e.into());
                }
            }
        }
        Err(VoirsError::G2pError(e)) => {
            eprintln!("โŒ G2P conversion failed: {}", e);
            eprintln!("๐Ÿ’ก Tip: Check if the text contains unsupported characters");
            return Err(e.into());
        }
        Err(VoirsError::AcousticError(e)) => {
            eprintln!("โŒ Acoustic model failed: {}", e);
            eprintln!("๐Ÿ’ก Tip: Ensure sufficient memory and valid model files");
            return Err(e.into());
        }
        Err(VoirsError::VocoderError(e)) => {
            eprintln!("โŒ Vocoder failed: {}", e);
            eprintln!("๐Ÿ’ก Tip: Check vocoder model compatibility");
            return Err(e.into());
        }
        Err(e) => {
            eprintln!("โŒ Synthesis error: {}", e);
            return Err(e.into());
        }
    }

    Ok(())
}

async fn create_synthesis_pipeline() -> Result<VoirsPipeline> {
    let g2p = create_g2p(G2pBackend::RuleBased)
        .context("Failed to create G2P component")?;

    let acoustic = create_acoustic(AcousticBackend::Vits)
        .context("Failed to create acoustic model")?;

    let vocoder = create_vocoder(VocoderBackend::HifiGan)
        .context("Failed to create vocoder")?;

    VoirsPipelineBuilder::new()
        .with_g2p(g2p)
        .with_acoustic_model(acoustic)
        .with_vocoder(vocoder)
        .build()
        .await
        .context("Failed to build synthesis pipeline")
}
```

## Configuration Options

### Voice Selection

Choose the right voice for your use case:

```rust
// For natural speech (high quality, slower)
let config = SynthesisConfig::default()
    .with_voice_quality(VoiceQuality::High)
    .with_model_size(ModelSize::Large);

// For balanced performance (good quality, moderate speed)
let config = SynthesisConfig::default()
    .with_voice_quality(VoiceQuality::Standard)
    .with_model_size(ModelSize::Base);

// For fast synthesis (lower quality, fastest)
let config = SynthesisConfig::default()
    .with_voice_quality(VoiceQuality::Fast)
    .with_model_size(ModelSize::Small);
```

### Audio Output

Configure audio output settings:

```rust
let config = SynthesisConfig::default()
    .with_sample_rate(22050)         // Standard quality
    .with_sample_rate(44100)         // High quality
    .with_channels(1)                // Mono output
    .with_bit_depth(16);             // 16-bit audio
```

### Synthesis Options

Control synthesis behavior:

```rust
let config = SynthesisConfig::default()
    .with_streaming_enabled(true)    // Enable streaming synthesis
    .with_ssml_enabled(true)         // Enable SSML markup
    .with_prosody_control(true)      // Enable prosody adjustments
    .with_emotion_control(true);     // Enable emotional expression
```

## Working with Examples

Explore the comprehensive examples included with VoiRS:

```bash
# Basic text-to-speech synthesis
cargo run --example simple_synthesis

# Batch processing
cargo run --example batch_synthesis

# Streaming synthesis
cargo run --example streaming_synthesis

# SSML support
cargo run --example ssml_synthesis

# Multi-language synthesis
cargo run --example multilingual_synthesis

# Performance testing
cargo run --example performance_benchmark

# Voice cloning (advanced)
cargo run --example voice_cloning --features="cloning"
```

## Next Steps

Now that you're familiar with the basics:

1. **Explore Advanced Features**: Check out [CLI Usage]./cli-usage.md for command-line tools
2. **Optimize Performance**: Read the [Performance Tuning]./performance.md guide
3. **Handle Edge Cases**: Review [Troubleshooting]./troubleshooting.md for common issues
4. **Build Applications**: See [Rust API]./rust-api.md for comprehensive API documentation
5. **Voice Customization**: Learn about [Voice Cloning]./voice-cloning.md and adaptation
6. **Production Deployment**: Review [Deployment Guide]./deployment.md for scalable setups

## Common Use Cases

### Voice Assistant Response

```rust
// Perfect for voice assistant responses
let config = SynthesisConfig::default()
    .with_streaming_enabled(true)
    .with_low_latency(true)
    .with_voice_quality(VoiceQuality::Standard);
```

### Audiobook Production

```rust
// Optimized for long-form content
let config = SynthesisConfig::default()
    .with_voice_quality(VoiceQuality::High)
    .with_ssml_enabled(true)
    .with_prosody_control(true);
```

### Real-time Narration

```rust
// For live narration applications
let config = SynthesisConfig::default()
    .with_streaming_enabled(true)
    .with_chunk_size(ChunkSize::Small)
    .with_buffer_optimization(true);
```

## Getting Help

- **Documentation**: Comprehensive guides in this documentation
- **Examples**: Working examples in the `examples/` directory
- **API Reference**: Complete API docs at [docs.rs/voirs]https://docs.rs/voirs
- **Community**: [GitHub Discussions]https://github.com/cool-japan/voirs/discussions
- **Issues**: [Bug Reports]https://github.com/cool-japan/voirs/issues
- **CLI Help**: Run `voirs --help` for command-line usage