Un cliente de voz no oficial de once laboratorios con un cliente RESTFUL.
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.
Instale el paquete ElevenLabs-DotNet desde Nuget. Así es como a través de la línea de comandos:
Install-Package ElevenLabs - DotNet dotnet add package ElevenLabs-DotNet
¿Buscas usar ElevenLabs en el motor Unity Game? Echa un vistazo a nuestro paquete Unity en OpenUpm:
Hay 3 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" ) ) ; 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 ( 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 ( ElevenLabsAuthentication . LoadFromEnv ( ) ) ;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.ElevenLabsClientSettings 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 ElevenLabsClientSettings ( 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 ValidateAuthentication . 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 ElevenLabsProxyStartup.CreateWebApplication Method, 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 auth = ElevenLabsAuthentication . LoadFromEnv ( ) ;
var client = new ElevenLabsClient ( auth ) ;
ElevenLabsProxyStartup . CreateWebApplication < AuthenticationFilter > ( args , client ) . 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.
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 ) ;
await File . WriteAllBytesAsync ( $ " { voiceClip . Id } .mp3" , voiceClip . ClipData . ToArray ( ) ) ; 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 ( ) ;
string fileName = "myfile.mp3" ;
using var outputFileStream = File . OpenWrite ( fileName ) ;
var request = new TextToSpeechRequest ( voice , text ) ;
var voiceClip = await api . TextToSpeechEndpoint . TextToSpeechAsync ( request ,
partialClipCallback : async ( partialClip ) =>
{
// Write the incoming data to the output file stream.
// Alternatively you can play this clip data directly.
await outputFileStream . WriteAsync ( partialClip . ClipData ) ;
} ) ;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 )
{
Console . WriteLine ( $ " { voice . OwnerId } | { voice . VoiceId } | { voice . Date } | { voice . Name } " ) ;
} Obtiene una lista de todas las voces disponibles disponibles para su cuenta.
var api = new ElevenLabsClient ( ) ;
var allVoices = await api . VoicesEndpoint . GetAllVoicesAsync ( ) ;
foreach ( var voice in allVoices )
{
Console . WriteLine ( $ " { 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 ( ) ;
Console . WriteLine ( $ "stability: { result . Stability } | similarity boost: { result . SimilarityBoost } " ) ; var api = new ElevenLabsClient ( ) ;
var voice = await api . VoicesEndpoint . GetVoiceAsync ( "voiceId" ) ;
Console . WriteLine ( $ " { 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 ) ) ;
Console . WriteLine ( $ "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 ) ;
Console . WriteLine ( $ "Was successful? { success } " ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . VoicesEndpoint . DeleteVoiceAsync ( voiceId ) ;
Console . WriteLine ( $ "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 ) ;
await File . WriteAllBytesAsync ( $ " { voiceClip . Id } .mp3" , voiceClip . ClipData . ToArray ( ) ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . VoicesEndpoint . DeleteVoiceSampleAsync ( voiceId , sampleId ) ;
Console . WriteLine ( $ "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" :
Console . WriteLine ( $ "Dubbing for { metadata . DubbingId } in progress... Expected Duration: { metadata . ExpectedDurationSeconds : 0.00 } seconds" ) ;
break ;
case "dubbed" :
Console . WriteLine ( $ "Dubbing for { metadata . DubbingId } complete in { metadata . TimeCompleted . TotalSeconds : 0.00 } seconds!" ) ;
break ;
default :
Console . WriteLine ( $ "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 el archivo doblado como un archivo transmitido.
Nota
Los videos se devolverán en formato MP4 y solo se devolverán los Dubs en MP3.
var assetsDir = Path . GetFullPath ( "../../../Assets" ) ;
var dubbedPath = new FileInfo ( Path . Combine ( assetsDir , $ "online.dubbed. { request . TargetLanguage } .mp4" ) ) ;
{
await using var fs = File . Open ( dubbedPath . FullName , FileMode . Create ) ;
await foreach ( var chunk in ElevenLabsClient . DubbingEndpoint . GetDubbedFileAsync ( metadata . DubbingId , request . TargetLanguage ) )
{
await fs . WriteAsync ( chunk ) ;
}
} Devuelve la transcripción para el DUB en el formato deseado.
var assetsDir = Path . GetFullPath ( "../../../Assets" ) ;
var transcriptPath = new FileInfo ( Path . Combine ( assetsDir , $ "online.dubbed. { request . TargetLanguage } .srt" ) ) ;
{
var transcriptFile = await api . 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 ) )
{
Console . WriteLine ( $ " { 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 ) ;
await File . WriteAllBytesAsync ( $ " { voiceClip . Id } .mp3" , voiceClip . ClipData . ToArray ( ) ) ; Descarga los últimos 100 elementos del historial o la colección de elementos especificados.
var api = new ElevenLabsClient ( ) ;
var voiceClips = await api . HistoryEndpoint . DownloadHistoryItemsAsync ( ) ; var api = new ElevenLabsClient ( ) ;
var success = await api . HistoryEndpoint . DeleteHistoryItemAsync ( historyItem ) ;
Console . WriteLine ( $ "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 ( ) ;