Search code examples
javascriptiosuiwebviewtext-to-speechspeech-synthesis

Setting rate, pitch, volume with speechSynthesis API in UIWebView for iOS 7+


I am trying to use UIWebView to do some simple TTS (Text to Speech) in my iOS App. From what I understand iOS 7 WebKit now supports it, so therefore the following below works:

   - (void) speakThis: (NSString*) text {
        [webview stringByEvaluatingJavaScriptFromString:
        [NSString stringWithFormat:
           @"speechSynthesis.speak(new SpeechSynthesisUtterance(\"%@\"));",
              text]];
    }

However I want to set the speech rate, pitch, and volume in the javascript as well. How would I go about doing that all in one simple line.

I know I can set properties like below:

var speech = new SpeechSynthesisUtterance();
speech.text = "Hello";
speech.volume = 1; // 0 to 1
speech.rate = 1; // 0.1 to 9
speech.pitch = 1; // 0 to 2, 1=normal
speech.lang = "en-US";
speechSynthesis.speak(speech);

But I want to pass in the pitch, volume, and rate in one init when I call

new SpeechSynthesisUtterance("")

Anyone, please assist?


Solution

  • You don't need to use a UIWebView. I was just investigating this, and found the API doc: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVSpeechSynthesizer_Ref/Reference/Reference.html#//apple_ref/occ/cl/AVSpeechSynthesizer