Wednesday 13 May 2015

Text to Speech in Javascript example for Web

Text to speech in HTML5 ,JavaScript which runs on all browser

Using Speech Synthesis in HTML5 we can convert Text to Audio (text to speech) in Javascript. It works in Chrome 33 (mobile and desktop).

The basic code speechSynthesis.speak() allow us to perform this task
var msg = new SpeechSynthesisUtterance('Hello World');

However, you can also alter parameters to effect the volume, speech rate, pitch, voice, and language:
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
msg.text = 'Hello World';
msg.lang = 'en-US';

msg.onend = function(e) {
  console.log('Finished in ' + event.elapsedTime + ' seconds.');


Browser Support

Chrome 33 has full support for the Web Speech API, while Safari for iOS7 has partial support.

Feature detection

Since browsers may support each portion of the Web Speech API separately (e.g. the case with Chromium), you may want to feature detect each feature separately:
if ('speechSynthesis' in window) {
 // Synthesis support. Make your web apps talk!

if ('SpeechRecognition' in window) {
  // Speech recognition support. Talk to your apps!