Using Safari's Text-to-Speech to Read Aloud HTML

PC/Etc
2013-11-01 16:22 (11 years ago) ytyng

Basically, you can make it speak with just this code:

var ssu = new SpeechSynthesisUtterance('Hello, World');
window.speechSynthesis.speak(ssu);

This is the kind of code I wrote. For mobile, since it's fast, I set the rate to 0.6.

For ssu.lang, you can set it to "en-US" or "ja-JP".

Since it can be triggered from HTML, it can also read aloud iBooks created in EPUB format, so its range of applications is broad.

To stop it, use window.speechSynthesis.cancel().

It might also work from UIWebView.

I've only tested it on iOS7 and above.

<script type="text/javascript">
  function getSpeechRate(){
      var userAgent = window.navigator.userAgent.toLowerCase();
      if (userAgent.indexOf('iphone') != -1 || userAgent.indexOf('ipad') != -1 ||
          userAgent.indexOf('ipod') != -1) {
          return 0.6;
      }
      return 1;
  }

  function speech() {
    text = document.getElementById('text-box').value;
    var ssu = new SpeechSynthesisUtterance(text);
    ssu.volume = 1;
    ssu.rate = getSpeechRate();
    ssu.pitch = 1;
    ssu.lang = document.getElementById('language-selector').value;
    window.speechSynthesis.speak(ssu);
  }

</script>

By the way, this is the user agent for iBooks on Mac OSX 10.9:

mozilla/5.0 (macintosh; intel mac os x 10_9) applewebkit/537.71 (khtml, like gecko)

And this is the user agent for iBooks on iOS7 iPad:

mozilla/5.0 (ipad; cpu os 7_0_3 like mac os x) applewebkit/537.51.1 (khtml, like gecko) mobile/11b511
Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011