Skip to content

Instantly share code, notes, and snippets.

@akeller akeller/testscript.cs
Last active Nov 4, 2019

Embed
What would you like to do?
Updated Text to Speech Example with the Watson SDK for Unity - works with unity sdk 3.1.0 (2019-04-09) & Unity core sdk 0.2.0 (2019-04-09)
using System.Collections;
using UnityEngine;
using IBM.Watson.TextToSpeech.V1;
using IBM.Cloud.SDK;
using IBM.Cloud.SDK.Utilities;
public class testscript : MonoBehaviour
{
#region PLEASE SET THESE VARIABLES IN THE INSPECTOR
[Header("Text to Speech")]
[SerializeField]
[Tooltip("The service URL (optional). This defaults to \"https://stream.watsonplatform.net/text-to-speech/api\"")]
private string TextToSpeechURL;
[Header("IAM Authentication")]
[Tooltip("The IAM apikey.")]
[SerializeField]
private string TextToSpeechIamApikey;
[Tooltip("The IAM url used to authenticate the apikey (optional). This defaults to \"https://iam.bluemix.net/identity/token\".")]
[SerializeField]
private string TextToSpeechIamUrl;
#endregion
private TextToSpeechService textToSpeech;
void Start()
{
LogSystem.InstallDefaultReactors();
Runnable.Run(CredentialCheck());
}
public IEnumerator CredentialCheck()
{
Credentials credentials = null;
//Authenticate using iamApikey
TokenOptions tokenOptions = new TokenOptions()
{
IamApiKey = TextToSpeechIamApikey
};
credentials = new Credentials(tokenOptions, TextToSpeechURL);
while (!credentials.HasIamTokenData())
yield return null;
textToSpeech = new TextToSpeechService(credentials);
Runnable.Run(CallTextToSpeech("Hello there, this is Watson!"));
}
public IEnumerator CallTextToSpeech(string outputText)
{
byte[] synthesizeResponse = null;
AudioClip clip = null;
textToSpeech.Synthesize(
callback: (DetailedResponse<byte[]> response, IBMError error) =>
{
synthesizeResponse = response.Result;
clip = WaveFile.ParseWAV("myClip", synthesizeResponse);
PlayClip(clip);
},
text: outputText,
voice: "en-US_AllisonVoice",
accept: "audio/wav"
);
while (synthesizeResponse == null)
yield return null;
yield return new WaitForSeconds(clip.length);
}
private void PlayClip(AudioClip clip)
{
if (Application.isPlaying && clip != null)
{
GameObject audioObject = new GameObject("AudioObject");
AudioSource source = audioObject.AddComponent<AudioSource>();
source.spatialBlend = 0.0f;
source.loop = false;
source.clip = clip;
source.Play();
GameObject.Destroy(audioObject, clip.length);
}
}
}
@renanmgs

This comment has been minimized.

Copy link

renanmgs commented Nov 4, 2019

Dosent work anymore

@akeller

This comment has been minimized.

Copy link
Owner Author

akeller commented Nov 4, 2019

Last tested with unity sdk 3.1.0 (2019-04-09) & Unity core sdk 0.2.0 (2019-04-09)

I no longer work with the Unity SDK do you'll need to make the updates on your own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.