Search code examples
text-to-speechspeech-synthesismarytts

Mary TTS with HTML/JavaScript and PHP


I installed Mary TTS (version 5.1.2) on my Windows (and Linux computers). I started the Mary TTS server and the Mary TTS client, and I did some trials with text to audio conversion in the GUI window (its great).

I would like to use Mary TTS on my website to read text aloud, where a user can add a text into the input field and generate the output like in the GUI window, without using the java client.

For example:

<input type="text" id="text">
<button onclick="play('text');">Speak it</button>

<script>
function play(id){
    var text = document.getElementById(id).value;
    var a = new Audio(text);
        a.play();
    }
</script>

Just to get started.. I can't realize how to do that in HTML/JavaScript and PHP?


Solution

  • Step 1. Host MaryTTS on a server

    I wrote marytts-http to wraps MaryTTS so it's easy to deploy to Heroku, though you could deploy it to other servers as well.

    First you'll need an account with Heroku, then install their toolbelt and run heroku login.

    After that you can deploy marytts-http to Heroku like this:

    git clone https://github.com/draffensperger/marytts-http
    cd marytts-http
    heroku create
    git push heroku master
    

    Step 2. Use your hosted MaryTTS instance in your website

    Heroku will give a name to your marytts-http instance that you created above which you can change later on the Heroku dashboard. Let's say the name of your instance is my-marytts, then the URL to get a text-to-speech audio file would be my-marytts.herokuapp.com/?text=Hello (just specify the text query parameter).

    To embed the audio on your website you should use an <audio> tag, e.g.:

    <audio src="my-marytts.herokuapp.com/?text=Hello" autoplay></audio>
    

    The autoplay makes it start the audio when the element is loaded. So in your case, what you could do is dynamically add an <audio> element after the user clicks the button, e.g.:

    <input type="text" id="text">
    <button onclick="play('text');">Speak it</button>
    
    <span id="audio-container" style="display:none;"></span>
    
    <script>
    function play(id) {
      var maryttsHost = 'https://example-mary-tts.herokuapp.com'
      var text = document.getElementById(id).value;
      var container = document.getElementById("audio-container");
      var audioSrc = maryttsHost + '/?text=' + encodeURIComponent(text);
      container.innerHTML = '<audio src="' + audioSrc + '" autoplay></audio>';
    }
    </script>
    

    You would need to change maryttsHost above to match the actual URL of your marytts-http instance on Heroku.