Skip to content

Instantly share code, notes, and snippets.

@Bunkerbewohner
Last active October 27, 2017 14:15
Show Gist options
  • Save Bunkerbewohner/7c453c5fca4f2889712cc62f68068908 to your computer and use it in GitHub Desktop.
Save Bunkerbewohner/7c453c5fca4f2889712cc62f68068908 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Goldsaucer.Askutron.TTS
{
public class TextToSpeech
{
private const string ServerUrl = "https://example.com";
public readonly string Text;
public readonly string Language;
public readonly string AudioUri;
public AudioClip AudioClip { get; private set; }
public TextToSpeech(string text, string language, string audioUri = null)
{
Text = text;
Language = language;
AudioUri = audioUri;
}
/// <summary>
/// Generate HTTP headers required to fetch audio from the server.
/// </summary>
/// <param name="phrase">text for which to download the audio</param>
/// <returns>A dictionary with the HTTP headers</returns>
private static Dictionary<string, string> GenerateRequestHeaders(TextToSpeech phrase)
{
var headers = new Dictionary<string, string>();
// [...] add required authentication headers etc.
return headers;
}
/// <summary>
/// Load the question's audio
/// </summary>
public IEnumerator Load()
{
var uri = AudioUri ?? $"/audios/playback?ssmd={Uri.EscapeUriString(Text)}&language={Language}";
var headers = GenerateRequestHeaders(this);
var request = new WWW(ServerUrl + uri, null, headers);
yield return request;
AudioClip = request.GetAudioClipCompressed(false, AudioType.OGGVORBIS);
}
/// <summary>
/// Read the question out aloud
/// </summary>
public IEnumerator Play()
{
AudioSource.PlayClipAtPoint(AudioClip, Vector3.zero);
yield return new WaitForSeconds(AudioClip.length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment