Un cliente de Síntesis de voz de once no oficial para el motor de juego Unity.
Basado en ElevenLabs-Dotnet
No estoy afiliado a ElevenLabs y se requiere una cuenta con acceso a la API.
Todos los derechos de autor, marcas comerciales, logotipos y activos son propiedad de sus respectivos propietarios.
Requiere Unity 2021.3 LTS o superior.
El método de instalación recomendado es a pesar de que Unity Package Manager y OpenUpm.
Package Manager 
OpenUPMhttps://package.openupm.comcom.rest.elevenlabscom.utilitiesMy RegistriesElevenLabshttps://github.com/RageAgainstThePixel/com.rest.elevenlabs.git#upmNota: ¡Este repositorio tiene dependencias de otros repositorios! Usted es responsable de agregarlos por su cuenta.
Hay 4 formas de proporcionar sus claves API, en orden de precedencia:
var api = new ElevenLabsClient ( "yourApiKey" ) ; O cree un objeto ElevenLabsAuthentication manualmente
var api = new ElevenLabsClient ( new ElevenLabsAuthentication ( "yourApiKey" ) ) ; Puede guardar la clave directamente en un objeto scriptable que se encuentra en la carpeta de Assets/Resources .
Puede crear uno nuevo utilizando el menú contextual del panel de proyecto y creando un nuevo objeto scriptable ElevenLabsConfiguration .

Intenta cargar claves API desde un archivo de configuración, de forma predeterminada .elevenlabs en el directorio actual, atravesando opcionalmente el árbol del directorio o en el directorio de inicio del usuario.
Para crear un archivo de configuración, cree un nuevo archivo de texto llamado .elevenlabs y contenga la línea:
{
"apiKey" : " yourApiKey " ,
}También puede cargar el archivo directamente con la ruta conocida llamando a un método estático en la autenticación:
var api = new ElevenLabsClient ( new ElevenLabsAuthentication ( ) . LoadFromDirectory ( "your/path/to/.elevenlabs" ) ) ; ; Use las variables de entorno de su sistema especifique una clave API para usar.
ELEVEN_LABS_API_KEY para su clave API. var api = new ElevenLabsClient ( new ElevenLabsAuthentication ( ) . LoadFromEnvironment ( ) ) ;Usar los paquetes ElevenLabs-Dotnet o Com.Rest.ElevenLabs directamente en su aplicación front-end puede exponer sus claves API y otra información confidencial. Para mitigar este riesgo, se recomienda configurar una API intermedia que realice solicitudes a once en nombre de su aplicación front-end. Esta biblioteca se puede utilizar para configuraciones de host front-end e intermediarias, asegurando una comunicación segura con la API de ElevenLabs.
En el ejemplo de front -end, deberá autenticar de forma segura a sus usuarios utilizando su proveedor de OAuth preferido. Una vez que el usuario esté autenticado, intercambie su token de autenticación personalizado con su clave API en el backend.
Sigue estos pasos:
ElevenLabsAuthentication y pase en el token personalizado.ElevenLabsSettings y especifique el dominio donde se encuentra su API intermedia.auth y objetos settings al constructor ElevenLabsClient cuando cree la instancia del cliente.Aquí hay un ejemplo de cómo configurar la parte delantera:
var authToken = await LoginAsync ( ) ;
var auth = new ElevenLabsAuthentication ( authToken ) ;
var settings = new ElevenLabsSettings ( domain : "api.your-custom-domain.com" ) ;
var api = new ElevenLabsClient ( auth , settings ) ;Esta configuración permite que su aplicación front-end se comunique de forma segura con su backend que utilizará el ElevenLabs-Dotnet-Proxy, que luego reenvía las solicitudes a la API de ElevenLabs. Esto garantiza que sus teclas API de ElevenLabs y otra información confidencial sigan siendo seguras durante todo el proceso.
En este ejemplo, demostramos cómo configurar y usar ElevenLabsProxyStartup en una nueva aplicación ASP.NET Core Web. El servidor proxy manejará la autenticación y reenviará las solicitudes a la API de ElevenLabs, asegurando que sus claves API y otra información confidencial permanezcan seguros.
Install-Package ElevenLabs-DotNet-Proxydotnet add package ElevenLabs-DotNet-Proxy<PackageReference Include="ElevenLabs-DotNet-Proxy" />AbstractAuthenticationFilter y anule el método ValidateAuthenticationAsync . Esto implementará el IAuthenticationFilter que usará para verificar el token de sesión de usuario en su servidor interno.Program.cs , cree una nueva aplicación web proxy llamando al método ElevenLabsProxyStartup.CreateDefaultHost , pasando su AuthenticationFilter personalizado como un argumento de tipo.ElevenLabsAuthentication y ElevenLabsClientSettings , como lo haría normalmente con sus claves API, ID de orgía o configuración de Azure. public partial class Program
{
private class AuthenticationFilter : AbstractAuthenticationFilter
{
public override async Task ValidateAuthenticationAsync ( IHeaderDictionary request )
{
await Task . CompletedTask ; // remote resource call
// You will need to implement your own class to properly test
// custom issued tokens you've setup for your end users.
if ( ! request [ "xi-api-key" ] . ToString ( ) . Contains ( TestUserToken ) )
{
throw new AuthenticationException ( "User is not authorized" ) ;
}
}
}
public static void Main ( string [ ] args )
{
var client = new ElevenLabsClient ( ) ;
var proxy = ElevenLabsProxyStartup . CreateDefaultHost < AuthenticationFilter > ( args , client ) ;
proxy . Run ( ) ;
}
}Una vez que haya configurado su servidor proxy, sus usuarios finales ahora pueden realizar solicitudes autenticadas a su API proxy en lugar de directamente a la API de ElevenLabs. El servidor proxy manejará la autenticación y reenviará las solicitudes a la API de ElevenLabs, asegurando que sus claves API y otra información confidencial permanezcan seguros.
¡Puede realizar todas las mismas acciones desde el sitio web de ElevenLabs, en el editor utilizando el Panel de ElevenLabs!
Window/Dashboards/ElevenLabs

Al igual que en el sitio web de ElevenLabs, puede sintetizar nuevos clips de audio utilizando las voces disponibles. Esta herramienta lo hace aún más útil ya que los clips se descargan e importan automáticamente en su proyecto, ¡listo para que lo use!

Al igual que en el sitio web de ElevenLabs, puede administrar todas sus voces directamente en el editor.

Seleccionar Create New Voice mostrará una ventana emergente donde puede diseñar voces completamente nuevas utilizando modelos generativos de ElevenLabs.

Además, también puede clonar una voz de las grabaciones de muestra.

También tiene acceso a la lista completa de todas sus muestras generadas, listas para descargar.

Convertir el texto al habla.
var api = new ElevenLabsClient ( ) ;
var text = "The quick brown fox jumps over the lazy dog." ;
var voice = ( await api . VoicesEndpoint . GetAllVoicesAsync ( ) ) . FirstOrDefault ( ) ;
var request = new TextToSpeechRequest ( voice , text ) ;
var voiceClip = await api . TextToSpeechEndpoint . TextToSpeechAsync ( request ) ;
audioSource . PlayOneShot ( voiceClip . AudioClip ) ;Nota: Si desea guardar el clip de voz en su proyecto, deberá copiarlo desde la ruta en caché en la ubicación especificada en su proyecto:
voiceClip . CopyIntoProject ( editorDownloadDirectory ) ; Transmitir texto al habla.
var api = new ElevenLabsClient ( ) ;
var text = "The quick brown fox jumps over the lazy dog." ;
var voice = ( await api . VoicesEndpoint . GetAllVoicesAsync ( ) ) . FirstOrDefault ( ) ;
var partialClips = new Queue < VoiceClip > ( ) ;
var request = new TextToSpeechRequest ( voice , message , model : Model . EnglishTurboV2 , outputFormat : OutputFormat . PCM_44100 ) ;
var voiceClip = await api . TextToSpeechEndpoint . StreamTextToSpeechAsync ( request , partialClip =>
{
// Note: check demo scene for best practices
// on how to handle playback with OnAudioFilterRead
partialClips . Enqueue ( partialClip ) ;
} ) ;Acceso a las voces creadas por el usuario o de ElevenLabs.
Obtiene una lista de voces compartidas en la biblioteca de voz pública.
var api = new ElevenLabsClient ( ) ;
var results = await ElevenLabsClient . SharedVoicesEndpoint . GetSharedVoicesAsync ( ) ;
foreach ( var voice in results . Voices )
{
Debug . Log ( $ " { voice . OwnerId } | { voice . VoiceId } | { voice . Date } | { voice . Name } " ) ;
} Obtiene una lista de todas las voces disponibles.
var api = new ElevenLabsClient ( ) ;
var allVoices = await api . VoicesEndpoint . GetAllVoicesAsync ( ) ;
foreach ( var voice in allVoices )
{
Debug . Log ( $ " { voice . Id } | { voice . Name } | similarity boost: { voice . Settings ? . SimilarityBoost } | stability: { voice . Settings ? . Stability } " ) ;
} Obtiene la configuración global de voz predeterminada.
var api = new ElevenLabsClient ( ) ;
var result = await api . VoicesEndpoint . GetDefaultVoiceSettingsAsync ( ) ;
Debug . Log ( $ "stability: { result . Stability } | similarity boost: { result . SimilarityBoost } " ) ; var api = new ElevenLabsClient ( ) ;
var voice = await api . VoicesEndpoint . GetVoiceAsync ( "voiceId" ) ;
Debug . Log ( $ " { voice . Id } | { voice . Name } | { voice . PreviewUrl } " ) ; Edite la configuración para una voz específica.
var api = new ElevenLabsClient ( ) ;
var success = await api . VoicesEndpoint . EditVoiceSettingsAsync ( voice , new VoiceSettings ( 0.7f , 0.7f ) ) ;
Debug . Log ( $ "Was successful? { success } " ) ; var api = new ElevenLabsClient ( ) ;
var labels = new Dictionary < string , string >
{
{ "accent" , "american" }
} ;
var audioSamplePaths = new List < string > ( ) ;
var voice = await api . VoicesEndpoint . AddVoiceAsync ( "Voice Name" , audioSamplePaths , labels ) ; var api = new ElevenLabsClient ( ) ;
var labels = new Dictionary < string , string >
{
{ "age" , "young" }
} ;
var audioSamplePaths = new List < string > ( ) ;
var success = await api . VoicesEndpoint . EditVoiceAsync ( voice , audioSamplePaths , labels ) ;
Debug . Log ( $ "Was successful? { success } " ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . VoicesEndpoint . DeleteVoiceAsync ( voiceId ) ;
Debug . Log ( $ "Was successful? { success } " ) ; Acceso a sus muestras, creado por usted al clonar las voces.
var api = new ElevenLabsClient ( ) ;
var voiceClip = await api . VoicesEndpoint . DownloadVoiceSampleAsync ( voice , sample ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . VoicesEndpoint . DeleteVoiceSampleAsync ( voiceId , sampleId ) ;
Debug . Log ( $ "Was successful? { success } " ) ;Dubs proporcionó un archivo de audio o video en idioma dado.
var api = new ElevenLabsClient ( ) ;
// from URI
var request = new DubbingRequest ( new Uri ( "https://youtu.be/Zo5-rhYOlNk" ) , "ja" , "en" , 1 , true ) ;
// from file
var request = new DubbingRequest ( filePath , "es" , "en" , 1 ) ;
var metadata = await api . DubbingEndpoint . DubAsync ( request , progress : new Progress < DubbingProjectMetadata > ( metadata =>
{
switch ( metadata . Status )
{
case "dubbing" :
Debug . Log ( $ "Dubbing for { metadata . DubbingId } in progress... Expected Duration: { metadata . ExpectedDurationSeconds : 0.00 } seconds" ) ;
break ;
case "dubbed" :
Debug . Log ( $ "Dubbing for { metadata . DubbingId } complete in { metadata . TimeCompleted . TotalSeconds : 0.00 } seconds!" ) ;
break ;
default :
Debug . Log ( $ "Status: { metadata . Status } " ) ;
break ;
}
} ) ) ; Devuelve metadatos sobre un proyecto de doblaje, incluido si todavía está en progreso o no.
var api = new ElevenLabsClient ( ) ;
var metadata = api . await GetDubbingProjectMetadataAsync ( "dubbing - id");Devuelve la ruta de archivo doblado descargado.
Importante
Los videos se devolverán en formato MP4 y solo se devolverán los Dubs en MP3.
var dubbedClipPath = await ElevenLabsClient . DubbingEndpoint . GetDubbedFileAsync ( metadata . DubbingId , request . TargetLanguage ) ;
var dubbedClip = await Rest . DownloadAudioClipAsync ( $ "file:// { dubbedClipPath } " , AudioType . MPEG ) ;
audioSource . PlayOneShot ( dubbedClip ) ; Devuelve la transcripción para el DUB en el formato deseado.
var srcFile = new FileInfo ( audioPath ) ;
var transcriptPath = new FileInfo ( $ " { srcFile . FullName } .dubbed. { request . TargetLanguage } .srt" ) ;
var transcriptFile = await ElevenLabsClient . DubbingEndpoint . GetTranscriptForDubAsync ( metadata . DubbingId , request . TargetLanguage ) ;
await File . WriteAllTextAsync ( transcriptPath . FullName , transcriptFile ) ; Elimina un proyecto de doblaje.
var api = new ElevenLabsClient ( ) ;
await api . DubbingEndpoint . DeleteDubbingProjectAsync ( "dubbing-id" ) ;API que convierte el texto en sonidos y utiliza el modelo de audio AI más avanzado de la historia.
var api = new ElevenLabsClient ( ) ;
var request = new SoundGenerationRequest ( "Star Wars Light Saber parry" ) ;
var clip = await api . SoundGenerationEndpoint . GenerateSoundAsync ( request ) ;Acceso a sus clips de audio previamente sintetizados, incluidos sus metadatos.
Obtenga metadatos sobre todo su audio generado.
var api = new ElevenLabsClient ( ) ;
var historyItems = await api . HistoryEndpoint . GetHistoryAsync ( ) ;
foreach ( var item in historyItems . OrderBy ( historyItem => historyItem . Date ) )
{
Debug . Log ( $ " { item . State } { item . Date } | { item . Id } | { item . Text . Length } | { item . Text } " ) ;
} Obtenga información sobre un elemento específico.
var api = new ElevenLabsClient ( ) ;
var historyItem = await api . HistoryEndpoint . GetHistoryItemAsync ( voiceClip . Id ) ; var api = new ElevenLabsClient ( ) ;
var voiceClip = await api . HistoryEndpoint . DownloadHistoryAudioAsync ( historyItem ) ; Descarga los últimos 100 elementos del historial o la colección de elementos especificados.
var api = new ElevenLabsClient ( ) ;
var voiceClips = await api . HistoryEndpoint . DownloadHistoryItemsAsync ( ) ;Nota: Para copiar los clips directamente a su proyecto, también puede llamar:
VoiceClipUtilities . CopyIntoProject ( editorDownloadDirectory , downloadItems . ToArray ( ) ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . HistoryEndpoint . DeleteHistoryItemAsync ( historyItem ) ;
Debug . Log ( $ "Was successful? { success } " ) ;Acceso a la información de su usuario y el estado de suscripción.
Obtiene información sobre su cuenta de usuario con ElevenLabs.
var api = new ElevenLabsClient ( ) ;
var userInfo = await api . UserEndpoint . GetUserInfoAsync ( ) ; Obtiene información sobre su suscripción con ElevenLabs.
var api = new ElevenLabsClient ( ) ;
var subscriptionInfo = await api . UserEndpoint . GetSubscriptionInfoAsync ( ) ;