64

I need to play Google text-to-speech in JavaScript.
The idea is to use the web service:

http://translate.google.com/translate_tts?tl=en&q=This%20is%20just%20a%20test

And play it on a certian action, e.g. a button click.

But it seems that it is not like loading a normal wav/mp3 file:

<audio id="audiotag1" src="audio/example.wav" preload="auto"></audio>

<script type="text/javascript">
    function play() {
        document.getElementById('audiotag1').play();
    }
</script>

How can I do this?

Betamoo
  • 14,964
  • 25
  • 75
  • 109

7 Answers7

168

Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.

Here is a sample:

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

With this, perhaps you do not need to use a web service at all.

Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
29

Here is the code snippet I found:

var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
Betamoo
  • 14,964
  • 25
  • 75
  • 109
  • 3
    It seems that if you remove the 'dot' at the end it works fine, otherwise it's not playing the sound. – Diego Sep 17 '13 at 15:53
  • 5
    Keep in mind that Google Translate has a limit of ~100 letters. – niutech Jan 08 '14 at 01:25
  • 8
    It seems that Google will ban requests with a Referrer in the HTTP header. Is there a way to bypass that issue? – jichi Jan 31 '14 at 20:03
  • @jichi Take a look on [this answer](http://stackoverflow.com/a/25102474/713937) and comments to [this answer](http://stackoverflow.com/a/5885535/713937). – Piotr Sobczyk Aug 03 '14 at 07:13
  • 20
    As of today this doesn't seem to be working any more; I get 302 and then 403. – icedwater Jan 28 '16 at 13:59
  • Can I use a text as a src for this tag. Ex: "Today is wonderful" this has to be spoken by the audio.play ? – Vasanth Oct 28 '18 at 05:52
22

You can use the SpeechSynthesisUtterance with a function like say:

function say(m) {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[10];
  msg.voiceURI = "native";
  msg.volume = 1;
  msg.rate = 1;
  msg.pitch = 0.8;
  msg.text = m;
  msg.lang = 'en-US';
  speechSynthesis.speak(msg);
}

Then you only need to call say(msg) when using it.

Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
  • 1
    are you the same user as the JudahRR who wrote say.js? If so, you should disclose that affiliation. Also, probably no need to consume an external library for a 10 line function that just consumes the browser's native API anyway and doesn't need all of the default settings. – KyleMit Dec 23 '18 at 01:01
  • 1
    As this uses the google voices, is there any way to load other languages, like Danish? I tried 'da' and 'da-DK' but she still spoke English. I could use the other solutions here, but this options seem like the easiest one. – Leif Neland Apr 07 '21 at 00:51
16

Very easy with responsive voice. Just include the js and voila!

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />
ManuelC
  • 161
  • 1
  • 2
  • 4
    Important note here: Although this has interesting immediate results, it is using their API via `https://code.responsivevoice.org/getvoice.php` to generate voices and send them back as rendered audio. Their service is however not free for non commercial projects. – Jankapunkt Sep 05 '19 at 10:50
8

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
<button type="button" id='myvoice'>Listen to me</button>
h3t1
  • 1,126
  • 2
  • 18
  • 29
iamnonso
  • 105
  • 1
  • 4
7

The below JavaScript code sends "text" to be spoken/converted to mp3 audio to google cloud text-to-speech API and gets mp3 audio content as response back.

 var text-to-speech = function(state) {
    const url = 'https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=GOOGLE_API_KEY'
    const data = {
      'input':{
         'text':'Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets.'
      },
      'voice':{
         'languageCode':'en-gb',
         'name':'en-GB-Standard-A',
         'ssmlGender':'FEMALE'
      },
      'audioConfig':{
      'audioEncoding':'MP3'
      }
     };
     const otherparam={
        headers:{
           "content-type":"application/json; charset=UTF-8"
        },
        body:JSON.stringify(data),
        method:"POST"
     };
    fetch(url,otherparam)
    .then(data=>{return data.json()})
    .then(res=>{console.log(res.audioContent); })
    .catch(error=>{console.log(error);state.onError(error)})
  };
jkr
  • 630
  • 1
  • 11
  • 24
3

Run this code it will take input as audio(microphone) and convert into the text than audio play.

<!doctype HTML>
<head>
<title>MY Echo</title>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" />
<style type="text/css">
    body {
        font-family: verdana;
    }

    #result {
        height: 100px;
        border: 1px solid #ccc;
        padding: 10px;
        box-shadow: 0 0 10px 0 #bbb;
        margin-bottom: 30px;
        font-size: 14px;
        line-height: 25px;
    }

    button {
        font-size: 20px;
        position: relative;
        left: 50%;
    }
</style>

Speech to text converter in JS var r = document.getElementById('result');

    function startConverting() {
        if ('webkitSpeechRecognition' in window) {
            var speechRecognizer = new webkitSpeechRecognition();
            speechRecognizer.continuous = true;
            speechRecognizer.interimResults = true;
            speechRecognizer.lang = 'en-IN';
            speechRecognizer.start();
            var finalTranscripts = '';
            speechRecognizer.onresult = function(event) {
                var interimTranscripts = '';
                for (var i = event.resultIndex; i < event.results.length; i++) {
                    var transcript = event.results[i][0].transcript;
                    transcript.replace("\n", "<br>");
                    if (event.results[i].isFinal) {
                        finalTranscripts += transcript;
                        var speechresult = finalTranscripts;
                        console.log(speechresult);
                        if (speechresult) {
                            responsiveVoice.speak(speechresult, "UK English Female", {
                                pitch: 1
                            }, {
                                rate: 1
                            });
                        }
                    } else {
                        interimTranscripts += transcript;
                    }
                }
                r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
            };
            speechRecognizer.onerror = function(event) {};
        } else {
            r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
        }
    }
</script>
</body>

</html>
Varun Rajkumar
  • 374
  • 1
  • 4
  • 13
Gajender Singh
  • 1,285
  • 14
  • 13