Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- using UnityEngine;
- namespace JasonStorey
- {
- public class ElevenLabs
- {
- readonly string _apiKey;
- HttpClient _client;
- const string DEFAULT_KEY = "YOUR_KEY";
- public ElevenLabs() : this(DEFAULT_KEY) { }
- public ElevenLabs(string apiKey)
- {
- _apiKey = apiKey;
- _client = new HttpClient();
- _client.DefaultRequestHeaders.Add("xi-api-key",_apiKey);
- _client.DefaultRequestHeaders.Add("x-api-key",_apiKey);
- }
- string ToMp3FileSave(HttpWebRequest req,string path)
- {
- HttpWebResponse response = (HttpWebResponse)req.GetResponse();
- // Get the stream associated with the response.
- Stream receiveStream = response.GetResponseStream();
- byte[] buffer = new byte[32768];
- using (FileStream fileStream = File.Create(path))
- {
- while (true)
- {
- int read = receiveStream.Read(buffer, 0, buffer.Length);
- if (read <= 0)
- break;
- fileStream.Write(buffer, 0, read);
- }
- }
- return path;
- }
- public async Task SaveToFile(string message,string path,Action<string> completed)
- {
- HttpResponseMessage result = (HttpResponseMessage)await Say(message,VOICE_AMY);
- var stream = await result.Content.ReadAsStreamAsync();
- byte[] buffer = new byte[32768];
- await using var fileStream = File.Create(path);
- while (true)
- {
- int read = await stream.ReadAsync(buffer, 0, buffer.Length);
- if (read <= 0)
- break;
- fileStream.Write(buffer, 0, read);
- }
- completed?.Invoke(path);
- }
- public async Task<object> Say(string message, string voice)
- {
- var json = JsonConvert.SerializeObject(TextRequest.Create(message));
- Debug.Log(json);
- var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
- return
- await _client.PostAsync("https://api.elevenlabs.io/v1/text-to-speech/" +
- voice, httpContent);
- }
- const string VOICE_AMY = "NUAlGdat74Sbul1N99HF";
- }
- [Serializable]
- public class TextRequest
- {
- public static TextRequest Create(string text) => new() { text = text, voice_settings = new VoiceSettings()};
- public string text;
- public VoiceSettings voice_settings;
- }
- [Serializable]
- public class VoiceSettings
- {
- public float similarity_boost = 0.7f;
- public float stability = 0.7f;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement