Rust AWS SDK Polly库的使用:AWS语音合成服务Polly的Rust集成与文本转语音功能实现

Rust AWS SDK Polly库的使用:AWS语音合成服务Polly的Rust集成与文本转语音功能实现

Amazon Polly是一项Web服务,可以轻松地将文本合成为语音。Amazon Polly服务提供了API操作,用于从纯文本和语音合成标记语言(SSML)合成高质量语音,以及管理发音词典,使您能够为应用程序领域获得最佳结果。

开始使用

SDK为每个AWS服务提供一个crate。您必须在Rust项目中添加Tokio作为依赖项以执行异步代码。要将aws-sdk-polly添加到您的项目中,请在Cargo.toml文件中添加以下内容:

[dependencies]
aws-config = { version = "1.1.7", features = ["behavior-version-latest"] }
aws-sdk-polly = "1.83.0"
tokio = { version = "1", features = ["full"] }

然后在代码中,可以使用以下方式创建客户端:

use aws_sdk_polly as polly;

#[::tokio::main]
async fn main() -> Result<(), polly::Error> {
    let config = aws_config::load_from_env().await;
    let client = aws_sdk_polly::Client::new(&config);

    // ... make some calls with the client

    Ok(())
}

完整示例:使用AWS Polly实现文本转语音

以下是一个完整的示例,展示如何使用Rust AWS SDK Polly库将文本转换为语音并保存为音频文件:

use aws_sdk_polly as polly;
use std::fs::File;
use std::io::Write;

#[tokio::main]
async fn main() -> Result<(), polly::Error> {
    // 加载AWS配置
    let config = aws_config::load_from_env().await;
    
    // 创建Polly客户端
    let client = polly::Client::new(&config);
    
    // 准备要合成的文本
    let text = "Hello, this is a sample text to be converted to speech using Amazon Polly.";
    
    // 构建合成语音请求
    let resp = client
        .synthesize_speech()
        .output_format(polly::types::OutputFormat::Mp3) // 设置输出格式为MP3
        .text(text) // 设置要合成的文本
        .voice_id(polly::types::VoiceId::Joanna) // 设置语音ID(使用Joanna声音)
        .send()
        .await?;
    
    // 获取音频流数据
    if let Some(audio_stream) = resp.audio_stream {
        let bytes = audio_stream.collect().await?;
        
        // 将音频数据写入文件
        let mut file = File::create("output.mp3")?;
        file.write_all(&bytes.into_bytes())?;
        
        println!("Audio file saved as output.mp3");
    }
    
    Ok(())
}

代码说明:

  1. 依赖和初始化

    • 使用aws-config加载AWS配置(从环境变量)
    • 创建Polly客户端
  2. 合成语音

    • 使用synthesize_speech()方法构建请求
    • 设置输出格式为MP3(OutputFormat::Mp3)
    • 设置要合成的文本内容
    • 选择语音ID(这里使用Joanna声音)
  3. 保存音频

    • 从响应中获取音频流数据
    • 将音频数据写入本地文件(output.mp3)

使用说明:

  1. 确保已配置AWS凭证(通过环境变量或~/.aws/credentials文件)
  2. 运行程序后,将在当前目录生成output.mp3音频文件
  3. 可以修改text变量内容来合成不同的语音
  4. 可以尝试不同的VoiceId来使用不同的声音(如Matthew, Salli等)

扩展示例:使用SSML和自定义参数

以下是一个更完整的示例,展示如何使用SSML和更多自定义参数:

use aws_sdk_polly as polly;
use std::fs::File;
use std::io::Write;

#[tokio::main]
async fn main() -> Result<(), polly::Error> {
    // 加载AWS配置
    let config = aws_config::load_from_env().await;
    let client = polly::Client::new(&config);

    // 使用SSML格式的文本
    let ssml_text = r#"<speak>
        <prosody rate="slow">Hello, this is a demonstration</prosody>
        <break time="500ms"/>
        <prosody pitch="high">of SSML capabilities</prosody>
        <break time="500ms"/>
        with Amazon Polly.
    </speak>"#;

    // 构建合成语音请求
    let resp = client
        .synthesize_speech()
        .output_format(polly::types::OutputFormat::Mp3)
        .text_type(polly::types::TextType::Ssml) // 指定使用SSML
        .text(ssml_text)
        .voice_id(polly::types::VoiceId::Matthew) // 使用Matthew声音
        .engine(polly::types::Engine::Neural) // 使用神经引擎
        .language_code("en-US") // 设置语言代码
        .send()
        .await?;

    // 获取并保存音频
    if let Some(audio_stream) = resp.audio_stream {
        let bytes = audio_stream.collect().await?;
        let mut file = File::create("enhanced_output.mp3")?;
        file.write_all(&bytes.into_bytes())?;
        println!("Enhanced audio file saved as enhanced_output.mp3");
    }

    Ok(())
}

新增功能说明:

  1. SSML支持

    • 使用text_type指定SSML格式
    • 支持SSML标签如<prosody><break>
  2. 高级参数

    • 指定神经引擎(Engine::Neural)
    • 设置语言代码
    • 使用男性声音(Matthew)
  3. 增强功能

    • 控制语速和音高
    • 添加停顿
    • 更自然的语音合成

许可证

该项目采用Apache-2.0许可证。


1 回复

Rust AWS SDK Polly库的使用:AWS语音合成服务Polly的Rust集成与文本转语音功能实现

介绍

AWS Polly是一项将文本转换为逼真语音的服务,Rust AWS SDK提供了对Polly服务的完整支持。通过这个库,Rust开发者可以轻松地将文本转语音功能集成到应用程序中。

使用方法

1. 添加依赖

首先在Cargo.toml中添加AWS SDK依赖:

[dependencies]
aws-config = "0.55"
aws-sdk-polly = "0.25"
tokio = { version = "1", features = ["full"] }

2. 基本配置

创建一个Polly客户端:

use aws_sdk_polly::Client;

async fn create_client() -> Client {
    let config = aws_config::load_from_env().await;
    Client::new(&config)
}

3. 文本转语音

简单文本转语音

use aws_sdk_polly::types::{OutputFormat, VoiceId};

async fn synthesize_speech(client: &Client, text: &str) -> Result<Vec<u8>, aws_sdk_polly::Error> {
    let resp = client
        .synthesize_speech()
        .output_format(OutputFormat::Mp3)
        .text(text)
        .voice_id(VoiceId::Joanna)
        .send()
        .await?;

    let audio = resp.audio_stream.collect().await?;
    Ok(audio.into_bytes())
}

使用示例

#[tokio::main]
async fn main() -> Result<(), aws_sdk_polly::Error> {
    let client = create_client().await;
    let text = "Hello, this is a test of the AWS Polly service from Rust!";
    
    let audio_data = synthesize_speech(&client, text).await?;
    
    // 保存到文件
    tokio::fs::write("output.mp3", audio_data).await?;
    
    println!("Audio file saved as output.mp3");
    Ok(())
}

4. 高级功能

获取可用语音列表

async fn list_voices(client: &Client) -> Result<(), aws_sdk_polly::Error> {
    let resp = client.describe_voices().send().await?;
    
    for voice in resp.voices().unwrap_or_default() {
        println!(
            "ID: {:?}, Language: {:?}, Name: {:?}",
            voice.id(),
            voice.language_code(),
            voice.name()
        );
    }
    
    Ok(())
}

使用SSML(语音合成标记语言)

async fn synthesize_ssml(client: &Client) -> Result<Vec<u8>, aws_sdk_polly::Error> {
    let ssml = r#"<speak>
        This is a normal voice. <amazon:effect name="whispered">This is a whisper.</amazon:effect>
        </speak>"#;

    let resp = client
        .synthesize_speech()
        .output_format(OutputFormat::Mp3)
        .text_type(aws_sdk_polly::types::TextType::Ssml)
        .text(ssml)
        .voice_id(VoiceId::Joanna)
        .send()
        .await?;

    let audio = resp.audio_stream.collect().await?;
    Ok(audio.into_bytes())
}

完整示例代码

use aws_sdk_polly::Client;
use aws_sdk_polly::types::{OutputFormat, VoiceId};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // 1. 创建Polly客户端
    let config = aws_config::load_from_env().await;
    let client = Client::new(&config);
    
    // 2. 列出可用语音
    println!("Available voices:");
    let voices = client.describe_voices().send().await?;
    for voice in voices.voices().unwrap_or_default() {
        println!(
            "ID: {:?}, Language: {:?}, Name: {:?}",
            voice.id(),
            voice.language_code(),
            voice.name()
        );
    }
    
    // 3. 普通文本转语音
    let text = "Hello, this is a test of the AWS Polly service from Rust!";
    println!("\nSynthesizing speech from text: {}", text);
    
    let audio_data = client
        .synthesize_speech()
        .output_format(OutputFormat::Mp3)
        .text(text)
        .voice_id(VoiceId::Joanna)
        .send()
        .await?
        .audio_stream
        .collect()
        .await?
        .into_bytes();
    
    tokio::fs::write("text_output.mp3", audio_data).await?;
    println!("Text speech saved to text_output.mp3");
    
    // 4. SSML文本转语音
    let ssml = r#"<speak>
        This is a normal voice. <amazon:effect name="whispered">This is a whisper.</amazon:effect>
        </speak>"#;
    println!("\nSynthesizing speech from SSML: {}", ssml);
    
    let ssml_data = client
        .synthesize_speech()
        .output_format(OutputFormat::Mp3)
        .text_type(aws_sdk_polly::types::TextType::Ssml)
        .text(ssml)
        .voice_id(VoiceId::Joanna)
        .send()
        .await?
        .audio_stream
        .collect()
        .await?
        .into_bytes();
    
    tokio::fs::write("ssml_output.mp3", ssml_data).await?;
    println!("SSML speech saved to ssml_output.mp3");
    
    Ok(())
}

最佳实践

  1. 缓存语音输出:对于静态文本,考虑缓存生成的语音以减少API调用和成本
  2. 错误处理:妥善处理API限制和错误响应
  3. 异步处理:使用Tokio等异步运行时处理长时间运行的语音合成任务
  4. 环境变量:通过.env文件或环境变量管理AWS凭证

注意事项

  • 确保已配置正确的AWS凭证(通过环境变量或AWS凭证文件)
  • 注意AWS Polly服务的定价和请求限制
  • 某些语音和功能可能仅在特定区域可用

通过Rust AWS SDK使用Polly服务,开发者可以轻松地为应用程序添加高质量的文本转语音功能,同时享受Rust的性能和安全性优势。

回到顶部