|
| 1 | +use std::fmt::Display; |
| 2 | + |
| 3 | +use base64::prelude::*; |
| 4 | +use futures_util::{SinkExt, StreamExt}; |
| 5 | +use reqwest_websocket::{RequestBuilderExt, WebSocket}; |
| 6 | + |
| 7 | +#[derive(Debug, serde::Deserialize)] |
| 8 | +pub struct Alignment { |
| 9 | + pub chars: Vec<String>, |
| 10 | +} |
| 11 | + |
| 12 | +#[derive(Debug, serde::Deserialize)] |
| 13 | +pub struct Response { |
| 14 | + #[serde(default)] |
| 15 | + pub alignment: Option<Alignment>, |
| 16 | + #[serde(default)] |
| 17 | + pub audio: Option<String>, |
| 18 | + #[serde(default, rename = "isFinal")] |
| 19 | + pub is_final: Option<bool>, |
| 20 | + #[serde(default)] |
| 21 | + pub error: String, |
| 22 | + #[serde(default)] |
| 23 | + pub message: String, |
| 24 | +} |
| 25 | + |
| 26 | +impl Response { |
| 27 | + pub fn is_error(&self) -> bool { |
| 28 | + !self.error.is_empty() |
| 29 | + } |
| 30 | + |
| 31 | + pub fn get_audio_bytes(&self) -> Option<Vec<u8>> { |
| 32 | + let _ = self.alignment.as_ref()?; |
| 33 | + self.audio |
| 34 | + .as_ref() |
| 35 | + .and_then(|audio_base64| BASE64_STANDARD.decode(audio_base64).ok()) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn is_final(&self) -> bool { |
| 39 | + self.is_final.unwrap_or(false) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +#[test] |
| 44 | +fn test_response_deserialize() { |
| 45 | + let json_data = r#" |
| 46 | + { |
| 47 | + "alignment": null, |
| 48 | + "audio": "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YRAAAAAA", |
| 49 | + "isFinal": null |
| 50 | + } |
| 51 | + "#; |
| 52 | + |
| 53 | + let response: Response = serde_json::from_str(json_data).unwrap(); |
| 54 | + println!("{:?}", response); |
| 55 | + assert!(!response.is_error()); |
| 56 | + assert!(!response.is_final()); |
| 57 | + assert!(response.get_audio_bytes().is_none()); |
| 58 | + |
| 59 | + let json_data_with_audio = r#" |
| 60 | + { |
| 61 | + "alignment": {}, |
| 62 | + "audio": "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YRAAAAAA", |
| 63 | + "isFinal": true |
| 64 | + } |
| 65 | + "#; |
| 66 | + |
| 67 | + let response_with_audio: Response = serde_json::from_str(json_data_with_audio).unwrap(); |
| 68 | + println!("{:?}", response_with_audio); |
| 69 | + assert!(!response_with_audio.is_error()); |
| 70 | + assert!(response_with_audio.is_final()); |
| 71 | + assert!(response_with_audio.get_audio_bytes().is_some()); |
| 72 | +} |
| 73 | + |
| 74 | +pub struct ElevenlabsTTS { |
| 75 | + pub token: String, |
| 76 | + pub voice: String, |
| 77 | + websocket: WebSocket, |
| 78 | +} |
| 79 | + |
| 80 | +const MODEL_ID: &str = "eleven_flash_v2_5"; |
| 81 | + |
| 82 | +pub enum OutputFormat { |
| 83 | + Pcm16000, |
| 84 | + Pcm24000, |
| 85 | +} |
| 86 | + |
| 87 | +impl Display for OutputFormat { |
| 88 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 89 | + match self { |
| 90 | + OutputFormat::Pcm16000 => write!(f, "pcm_16000"), |
| 91 | + OutputFormat::Pcm24000 => write!(f, "pcm_24000"), |
| 92 | + } |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +impl ElevenlabsTTS { |
| 97 | + pub async fn new( |
| 98 | + token: String, |
| 99 | + voice: String, |
| 100 | + output_format: OutputFormat, |
| 101 | + ) -> anyhow::Result<Self> { |
| 102 | + let url = format!( |
| 103 | + "wss://api.elevenlabs.io/v1/text-to-speech/{voice}/stream-input?model_id={MODEL_ID}&output_format={output_format}", |
| 104 | + ); |
| 105 | + |
| 106 | + let client = reqwest::Client::new(); |
| 107 | + |
| 108 | + let response = client |
| 109 | + .get(url) |
| 110 | + .header("xi-api-key", &token) |
| 111 | + .upgrade() |
| 112 | + .send() |
| 113 | + .await?; |
| 114 | + |
| 115 | + let websocket = response.into_websocket().await?; |
| 116 | + |
| 117 | + Ok(Self { |
| 118 | + token, |
| 119 | + voice, |
| 120 | + websocket, |
| 121 | + }) |
| 122 | + } |
| 123 | + |
| 124 | + pub async fn initialize_connection(&mut self) -> anyhow::Result<()> { |
| 125 | + let init_message = serde_json::json!({ |
| 126 | + "text": " ", |
| 127 | + }); |
| 128 | + |
| 129 | + let message_json = serde_json::to_string(&init_message)?; |
| 130 | + self.websocket |
| 131 | + .send(reqwest_websocket::Message::Text(message_json)) |
| 132 | + .await?; |
| 133 | + |
| 134 | + Ok(()) |
| 135 | + } |
| 136 | + |
| 137 | + pub async fn send_text(&mut self, text: &str, flush: bool) -> anyhow::Result<()> { |
| 138 | + let text_message = serde_json::json!({ |
| 139 | + "text": text, |
| 140 | + "flush": flush, |
| 141 | + }); |
| 142 | + |
| 143 | + let message_json = serde_json::to_string(&text_message)?; |
| 144 | + self.websocket |
| 145 | + .send(reqwest_websocket::Message::Text(message_json)) |
| 146 | + .await?; |
| 147 | + |
| 148 | + Ok(()) |
| 149 | + } |
| 150 | + |
| 151 | + pub async fn close_connection(&mut self) -> anyhow::Result<()> { |
| 152 | + let close_message = serde_json::json!({ |
| 153 | + "text": "", |
| 154 | + }); |
| 155 | + self.websocket |
| 156 | + .send(reqwest_websocket::Message::Text(close_message.to_string())) |
| 157 | + .await?; |
| 158 | + Ok(()) |
| 159 | + } |
| 160 | + |
| 161 | + pub async fn next_audio_response(&mut self) -> anyhow::Result<Option<Response>> { |
| 162 | + while let Some(message) = self.websocket.next().await { |
| 163 | + match message.map_err(|e| anyhow::anyhow!("Elevenlabs TTS WebSocket error: {}", e))? { |
| 164 | + reqwest_websocket::Message::Text(text) => { |
| 165 | + let response: Response = serde_json::from_str(&text).map_err(|e| { |
| 166 | + anyhow::anyhow!( |
| 167 | + "Failed to parse Elevenlabs TTS response: {}, error: {}", |
| 168 | + text, |
| 169 | + e |
| 170 | + ) |
| 171 | + })?; |
| 172 | + |
| 173 | + if response.is_error() { |
| 174 | + return Err(anyhow::anyhow!( |
| 175 | + "Elevenlabs TTS error: {}", |
| 176 | + response.message |
| 177 | + )); |
| 178 | + } |
| 179 | + |
| 180 | + if response.alignment.is_some() && response.audio.is_some() { |
| 181 | + log::trace!( |
| 182 | + "Elevenlabs TTS audio chunk received, size: {}", |
| 183 | + response.audio.as_ref().unwrap().len() |
| 184 | + ); |
| 185 | + return Ok(Some(response)); |
| 186 | + } |
| 187 | + |
| 188 | + if response.is_final() { |
| 189 | + log::trace!("TTS stream ended"); |
| 190 | + return Ok(None); |
| 191 | + } |
| 192 | + } |
| 193 | + reqwest_websocket::Message::Binary(_) => {} |
| 194 | + msg => { |
| 195 | + if cfg!(debug_assertions) { |
| 196 | + log::debug!("Received non-text message: {:?}", msg); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + } |
| 201 | + Ok(None) |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +#[tokio::test] |
| 206 | +async fn test_elevenlabs_tts() { |
| 207 | + env_logger::init(); |
| 208 | + let token = std::env::var("ELEVENLABS_API_KEY").unwrap(); |
| 209 | + let voice = std::env::var("ELEVENLABS_VOICE_ID").unwrap(); |
| 210 | + |
| 211 | + let mut tts = ElevenlabsTTS::new(token, voice, OutputFormat::Pcm16000) |
| 212 | + .await |
| 213 | + .expect("Failed to create ElevenlabsTTS"); |
| 214 | + |
| 215 | + tts.send_text("Hello, this is a test of Elevenlabs TTS.", true) |
| 216 | + .await |
| 217 | + .expect("Failed to send text"); |
| 218 | + |
| 219 | + tts.close_connection() |
| 220 | + .await |
| 221 | + .expect("Failed to close connection"); |
| 222 | + |
| 223 | + while let Ok(Some(resp)) = tts.next_audio_response().await { |
| 224 | + if let Some(audio) = resp.get_audio_bytes() { |
| 225 | + println!("Received audio chunk of size: {}", audio.len()); |
| 226 | + } |
| 227 | + } |
| 228 | + |
| 229 | + tts.close_connection() |
| 230 | + .await |
| 231 | + .expect("Failed to close connection"); |
| 232 | +} |
0 commit comments