Skip to content

Instantly share code, notes, and snippets.

@ceee
Last active May 25, 2016 11:46
Show Gist options
  • Save ceee/8235943 to your computer and use it in GitHub Desktop.
Save ceee/8235943 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Windows.Foundation;
using Windows.Phone.Speech.Synthesis;
namespace Utilities
{
public class SpeechUtility : IDisposable
{
protected SpeechSynthesizer synth;
protected string text;
protected string[] parts;
protected int max;
protected IAsyncAction speakTask;
public int Count { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SpeechUtility"/> class.
/// </summary>
/// <param name="text">The text.</param>
public SpeechUtility(string text)
{
synth = new SpeechSynthesizer();
this.text = text;
parts = this.text.Split(' '); // create a bookmark after each word
max = this.parts.Length;
synth.BookmarkReached += BookmarkReached;
}
/// <summary>
/// Speaks the text.
/// </summary>
/// <param name="start">The start count.</param>
/// <returns></returns>
public void Speak(int? start = null)
{
if (start.HasValue)
{
Count = start.Value;
}
speakTask = synth.SpeakSsmlAsync(CreateSSML());
}
/// <summary>
/// Pauses the speak task.
/// </summary>
/// <returns></returns>
public void Pause()
{
speakTask.Cancel();
}
/// <summary>
/// Creates the SSML.
/// </summary>
/// <returns></returns>
protected string CreateSSML()
{
// restart reading when the END was reached before
if (Count == max)
{
Count = 0;
}
String ssmlText = "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-US\">";
ssmlText += "<![CDATA[";
for (int i = Count; i < max; i++)
{
ssmlText += parts[i];
ssmlText += "]]><mark name=\"PART" + i.ToString() + "\"/><![CDATA[";
}
ssmlText += "]]><mark name=\"END\"/>";
ssmlText += "</speak>";
return ssmlText;
}
/// <summary>
/// Reached a new bookmark.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="SpeechBookmarkReachedEventArgs"/> instance containing the event data.</param>
protected void BookmarkReached(object sender, SpeechBookmarkReachedEventArgs e)
{
Count++;
if (e.Bookmark == "END")
{
Pause();
Count = 0;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
synth.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment