rust - 将流式未来对象的主体保存到磁盘
问题描述
我正在使用来自 rusoto 的PollyClient ,我正在尝试处理我认为Future
来自方法的某种类型的响应synthesize_speech()
。
这是我所拥有的按原样编译和运行的片段:
extern crate rusoto_core;
extern crate rusoto_polly;
use std::default::Default;
use tokio::{io};
use rusoto_core::credential::{ProfileProvider, ProvideAwsCredentials};
use rusoto_core::Region;
use rusoto_core::ByteStream;
use rusoto_polly::{PollyClient, SynthesizeSpeechInput, Polly};
use std::fs::File;
use futures::AsyncBufRead;
use std::pin::Pin;
use futures::Future;
fn main() {
let region = Region::UsEast1;
let polly_client = PollyClient::new(region); // using default credenetials
let speech_input = SynthesizeSpeechInput{
engine: Option::from(String::from("neural")),
language_code: None,
lexicon_names: None,
output_format: "mp3".to_string(),
sample_rate: None,
speech_mark_types: None,
text: String::from("hello world!"),
text_type: None,
voice_id: String::from("Amy")
};
let mut response = polly_client.synthesize_speech(speech_input);
println!("Now how to we handle this respones object...");
}
我的目标是在响应中保存应该是 MP3 二进制数据的内容。我没有分享任何编译器错误,因为我经历了很多不同的错误。我是 Rust 的新手,在开发非异步代码的同时,这是我第一次遇到它。
我是否需要将该synthesize_speech()
方法包装在闭包中,以便可以将其包装在某种await
块中?
任何帮助或建议将不胜感激。
解决方案
我意识到这只是一个玩具示例,但是在模仿了rusoto 文档async
中的一些 tokio模式之后,能够让它工作:main()
extern crate rusoto_core;
extern crate rusoto_polly;
// use rusoto_core::credential::{ProfileProvider, ProvideAwsCredentials};
use rusoto_core::{Region};
use rusoto_polly::{PollyClient, SynthesizeSpeechInput, Polly};
use std::fs;
#[tokio::main] // https://docs.rs/tokio/0.2.2/tokio/attr.main.html
async fn main() {
let region = Region::UsEast1;
let polly_client = PollyClient::new(region); // using default credentials
let speech_input = SynthesizeSpeechInput{
engine: Option::from(String::from("neural")),
language_code: None,
lexicon_names: None,
output_format: "mp3".to_string(),
sample_rate: None,
speech_mark_types: None,
text: String::from("Hello world, from Rust!"),
text_type: None,
voice_id: String::from("Amy")
};
match polly_client.synthesize_speech(speech_input).await {
Ok(output) => match output.audio_stream{
Some(audio_stream) => {
println!("{}", audio_stream.len());
fs::write("mp3/rstts.mp3", audio_stream).expect("Unable to write file");
},
None => println!("audio stream not found"),
},
Err(error) => {
println!("error: {:?}", error);
}
}
}
推荐阅读
- python - 解码器上采样大小
- javascript - Linking.openURL("https://www.google.com/") 无限循环(tabs) ,我怎样才能获得单身?
- typescript - 将特定类型分配给兼容对象
- quarkus - 似乎 jvm 参数不会被 quarkus 接受
- javascript - 如何将全局变量作为局部变量实现到这些函数中,或者如何将其变成 1 个完整函数?
- r - 整洁的 ggplot-esque 方式来绘制在每年开始时重新设置的时间序列
- django-rest-framework - Serializers 类的 update() 方法和 UpdateAPIView 有什么不同?
- entity-framework - 插入后缺少 EF Core 5 外键
- google-apps-script - 自动将值从一个列复制到另一个列并使其固定
- pine-script - 目标订单未完成