generated from RageAgainstThePixel/upm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for all multiple generation API features #98
Closed
tomkail
wants to merge
3
commits into
RageAgainstThePixel:development
from
tomkail:multiple_generations
Closed
Support for all multiple generation API features #98
tomkail
wants to merge
3
commits into
RageAgainstThePixel:development
from
tomkail:multiple_generations
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…us_request_ids and next_request_ids
Testing script here! // Licensed under the MIT License. See LICENSE in the project root for license information.
using ElevenLabs.Models;
using ElevenLabs.Voices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ElevenLabs.TextToSpeech;
using UnityEngine;
using Utilities.Async;
namespace ElevenLabs.Demo
{
[RequireComponent(typeof(AudioSource))]
public class TextToSpeechDemo : MonoBehaviour
{
[SerializeField]
private ElevenLabsConfiguration configuration;
[SerializeField]
private bool debug = true;
[SerializeField]
private Voice voice;
[SerializeField]
public Message[] messages;
[Serializable]
public class Message {
[TextArea(3, 10)]
public string message;
public string id;
public AudioClip audioClip;
}
[SerializeField]
private AudioSource audioSource;
private readonly Queue<AudioClip> streamClipQueue = new();
public Mode mode = Mode.GenerateLinear;
public enum Mode {
GenerateLinear,
GenerateRandom,
NoPreviousRequests,
}
#if !UNITY_2022_3_OR_NEWER
private readonly CancellationTokenSource lifetimeCts = new();
private CancellationToken destroyCancellationToken => lifetimeCts.Token;
#endif
private void OnValidate()
{
if (audioSource == null)
{
audioSource = GetComponent<AudioSource>();
}
}
void Start()
{
OnValidate();
RunAllIndicesAsync();
}
private async void RunAllIndicesAsync()
{
if (mode == Mode.GenerateLinear || mode == Mode.NoPreviousRequests) {
for (int i = 0; i < messages.Length; i++) {
if (!string.IsNullOrEmpty(messages[i].id)) continue;
var index = Array.IndexOf(messages, messages[i]);
await RunForIndexAsync(index);
if(lifetimeCts.Token.IsCancellationRequested) break;
}
}
else if (mode == Mode.GenerateRandom) {
var shuffledMessages = messages.OrderBy(x => Guid.NewGuid()).ToArray();
for (int i = 0; i < shuffledMessages.Length; i++) {
if (!string.IsNullOrEmpty(shuffledMessages[i].id)) continue;
var index = Array.IndexOf(messages, shuffledMessages[i]);
await RunForIndexAsync(index);
if(lifetimeCts.Token.IsCancellationRequested) break;
}
}
streamClipQueue.Clear();
var streamQueueCts = CancellationTokenSource.CreateLinkedTokenSource(destroyCancellationToken);
for (int i = 0; i < messages.Length; i++) {
streamClipQueue.Enqueue(messages[i].audioClip);
}
PlayStreamQueue(streamQueueCts.Token);
await new WaitUntil(() => streamClipQueue.Count == 0 && !audioSource.isPlaying);
streamQueueCts.Cancel();
}
private async Task RunForIndexAsync(int index)
{
try
{
var api = new ElevenLabsClient(configuration)
{
EnableDebug = debug
};
if (voice == null)
{
voice = (await api.VoicesEndpoint.GetAllVoicesAsync(destroyCancellationToken)).FirstOrDefault();
}
var voiceSettings = await api.VoicesEndpoint.GetVoiceSettingsAsync(voice.Id, destroyCancellationToken);
var request = new TextToSpeechRequest(voice, messages[index].message, Encoding.UTF8, voiceSettings, OutputFormat.MP3_44100_128, null, Model.TurboV2_5);
if (mode != Mode.NoPreviousRequests) {
request.PreviousText = index > 0 ? messages[index - 1].message : null;
request.NextText = index < messages.Length-1 ? messages[index + 1].message : null;
var previousRequestIds = new List<string>();
for(int i = 1; i <= 3; i++) {
var prevIndex = index - i;
if(prevIndex < 0 || string.IsNullOrEmpty(messages[prevIndex].id)) break;
previousRequestIds.Add(messages[prevIndex].id);
}
var nextRequestIds = new List<string>();
for (int i = 1; i <= 3; i++) {
var nextIndex = index + i;
if(nextIndex >= messages.Length || string.IsNullOrEmpty(messages[nextIndex].id)) break;
nextRequestIds.Add(messages[nextIndex].id);
}
request.PreviousRequestIds = previousRequestIds.ToArray();
request.NextRequestIds = nextRequestIds.ToArray();
}
var voiceClip = await api.TextToSpeechEndpoint.TextToSpeechAsync(request, cancellationToken: destroyCancellationToken);
messages[index].id = voiceClip.Id;
messages[index].audioClip = voiceClip.AudioClip;
// audioSource.PlayOneShot(voiceClip.AudioClip);
//
// await new WaitUntil(() => !audioSource.isPlaying);
if (debug)
{
Debug.Log($"Full clip: {voiceClip.Id}");
}
}
catch (Exception e)
{
Debug.LogError(e);
}
}
#if !UNITY_2022_3_OR_NEWER
private void OnDestroy()
{
lifetimeCts.Cancel();
lifetimeCts.Dispose();
}
#endif
private async void PlayStreamQueue(CancellationToken cancellationToken)
{
try
{
await new WaitUntil(() => streamClipQueue.Count > 0);
var endOfFrame = new WaitForEndOfFrame();
do
{
if (!audioSource.isPlaying &&
streamClipQueue.TryDequeue(out var clip))
{
Debug.Log($"playing partial clip: {clip.name}");
audioSource.PlayOneShot(clip);
}
await endOfFrame;
} while (!cancellationToken.IsCancellationRequested);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
} |
ElevenLabs/Packages/com.rest.elevenlabs/Runtime/TextToSpeech/TextToSpeechRequest.cs
Outdated
Show resolved
Hide resolved
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Removes previous_text from the constructor and adds next_text, previous_request_ids and next_request_ids