Friday, February 27, 2026

Speaking AI

For an index to all my stories click this text.

Let's do something fun.
This story shows how you can send a question to an AI chatbot and have the answer spoken out !! This story falls back on two previous stories.

The first one is building a webpage with JavaScript that accesses a simple AI system.
You can read that story here : https://lucstechblog.blogspot.com/2026/02/easy-ai-with-javascript.html

The second story shows how to use the VoiceRSS service to make your webpage generate spoken text.
You can read that story here: https://lucstechblog.blogspot.com/2026/02/text-to-speech-with-voicerss.html

How about typing a text on a webpage, send that text to an AI system and then send the answer to VoiceRSS. Our webpage then speaks out the audio received from VoiceRSS.

Actually this is quite simple to achieve. The only thing we need to do is to combine the programs of the two previous (above mentioned) stories.

First thing to do.

The first thing to do is to get your own API key from VoiceRSS. This was discussed in the following story:
https://lucstechblog.blogspot.com/2026/02/text-to-speech-with-voicerss.html
So make sure to carefully read that story and get your own API Key.

When you got the Key you can fill it in the next program.

The basic program.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset='utf-8' />
    <script src='voicerss-tts.min.js'></script>
</head>
<body>
    <script>
        VoiceRSS.speech({
            key: 'PUT-YOUR-API-KEY-HERE',
            src: 'Hello, world!',
            hl: 'en-us',
            v: 'Linda',
            r: 0,
            c: 'mp3',
            f: '44khz_16bit_stereo',
            ssml: false
        });
    </script>
</body>
</html>


Actually this program works and speaks out the words "Hello World"
So copy this and paste it in your favorite editor and then save it as an HTML file.
Do not forget to paste n your own API key where it says: PUT-YOUR-API-KEY-HERE

Click on the icon and your web browser will open and after a few seconds the text will be spoken. So make sure to turn the volume of your speakers up.

Sidenote.

The script (program) inside the webpage is Javascript. Javascript is actually not very complicated to use. And best part is that you can get immediate results on a simple webpage. However, Javascript is very versatile and can be used for all kinds of projects. To make programming with Javascript a lot easier I collected more then 500 programming tips and tricks and put them in a book. You can buy this book at Amazon and they ship worldwide.


Click here to learn more or buy this book.

The program looks and is very simple but that is because it imports a library from the internet.
The point is that I actually do not want to import a library.
Why ???
Well because it is totally unnecessary. You can use VoiceRSS with a simple fetch command.

So I wrote a complete program that is a webpage which has an input field in which you can type your question.

When you then press the send button the question is send to a simple AI system. The answer that the AI system sends back is then send to VoiceRSS. The answer is also saved in your downloads directory, as a wav file. This way you can use that audio file in other programs or projects.
The answer is then spoken out.

And there is an audio player at the bottom of the page that can replay the text that was spoken, it just gets the saved audio file and plays that again.

Here is the complete program:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Simple AI Fetch</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }

    textarea {
      width: 100%;
      min-height: 100px;
      resize: vertical;
      box-sizing: border-box;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 5px;
      overflow-y: auto;
    }

    button {
      margin-top: 10px;
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
    }

    pre {
      background: #f9f9f9;
      border: 1px solid #ddd;
      padding: 10px;
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    audio {
      margin-top: 10px;
      width: 100%;
    }
  </style>
</head>
<body>
  <h2>Ask a Question</h2>

  <!-- Replaced input with textarea -->
  <textarea id="userInput" placeholder="Type your question..."></textarea>
  <br>
  <button onclick="sendRequest()">Send</button>

  <h3>Response:</h3>
  <pre id="output"></pre>

  <audio id="audioPlayer" controls></audio>

  <script>
    async function sendRequest() {
      const userText = document.getElementById("userInput").value.trim();
      if (!userText) return alert("Please enter a question!");

      const targetUrl = "http://nimaartman.ir/science/L1.php?text=" +
                        encodeURIComponent("answerinenglishnoutf8anywhere.:" + userText);

      const proxyUrl = "https://api.allorigins.win/raw?url=" + encodeURIComponent(targetUrl);

      try {
        const response = await fetch(proxyUrl);
        const text = await response.text();

        let data;
        try {
          data = JSON.parse(text);
        } catch {
          data = { data: text };
        }

        let rec_ans = data.data || "";
        rec_ans = rec_ans.replace(/[^A-Za-z0-9 \n.,!?\\*+\-%@$&:<>()[\]{}"`]/g, "").trim();

        document.getElementById("output").textContent = rec_ans;
        console.log("Received Answer:", rec_ans);

        const API_KEY = 'YOUR-OWN-API-KEY-HERE';
        const url = 'https://api.voicerss.org/';

        const params = new URLSearchParams({
          key: API_KEY,
          hl: 'en-us',
          v: 'Amy',
          f: '8khz_16bit_mono',
          src: rec_ans || "I have turned the lights off"
        });

        const ttsResponse = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: params
        });

        if (!ttsResponse.ok) {
          console.error('❌ TTS request failed:', ttsResponse.status);
          return;
        }

        const audioBlob = await ttsResponse.blob();
        const audioUrl = URL.createObjectURL(audioBlob);

        const audioPlayer = document.getElementById("audioPlayer");
        audioPlayer.src = audioUrl;

        audioPlayer.play().catch(err => console.error("🎧 Playback error:", err));

        console.log("🎵 Playing audio...");


      //  Automatically trigger audio file download (no visible button)
      const downloadLink = document.createElement('a');
      downloadLink.href = audioUrl;
      downloadLink.download = `response_${Date.now()}.mp3`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      downloadLink.remove(); // clean up the temporary link


      } catch (error) {
        console.error('⚠️ Request failed:', error);
      }
    }
  </script>
</body>
</html>

Nothing dramatically complicated here.
I will just hi-lite a few sections.

      const targetUrl = "http://nimaartman.ir/science/L1.php?text=" +
                        encodeURIComponent("answerinenglishnoutf8anywhere.:" + userText);

This is the URL for the AI we are going to use for asking our questions.
But using this in a fetch command will throw a CORS error.
I have written about that in this story : https://lucstechblog.blogspot.com/2026/01/solving-cors-error-with-javascript.html

      const proxyUrl = "https://api.allorigins.win/raw?url=" + encodeURIComponent(targetUrl);

To avoid the CORS error we are going to use an external service called AllOrigins.
So we are going to wrap our fetch command into an AllOrigins fetch. Please read the story about this like stated above.

The AI system does not need you to log in or make an account. So you also do not need an API key for that.

But VoiceRSS does need an API key.
I wrote how to get that key in this story:
https://lucstechblog.blogspot.com/2026/02/text-to-speech-with-voicerss.html
So follow that to get your own key.

        const API_KEY = 'YOUR-OWN-API-KEY-HERE';

This is where you fill in your own API key for VoiceRSS.

        const params = new URLSearchParams({
          key: API_KEY,
          hl: 'en-us',
          v: 'Amy',
          f: '8khz_16bit_mono',
          src: rec_ans || "I have turned the lights off"
        });

This is where you set the language and voice. You can find all supported languages and voices on https://www.voicerss.org/api/

The rest is just the fetch command and the code for playing the audio.

How to use this.

Just copy the above code and paste it in your favorite editor. Then save it as spoken-ai.html or give it any name you like. Then open the directory where you saved it and click on the icon. Your default browser will open and show the webpage.




Put your question in the input field and press the send button. After a second or two the answer to your question will be spoken out. So turn up the volume of your speakers.

The audio file with the spoken text is saved to your download directory. And pressing the play button replays the audio (speaking the text) without the need to press the send button again.

Things to consider.

It takes a few seconds before the program starts speaking the answer to your question. Sometimes it takes just a second and sometimes it takes a few seconds.
This is because the program first has to access the AllOrigins API, then the AI and then access VoiceRSS. And sometimes (especially Allorigins) can get a bit busy.

And just sometimes it will not work at all.
Then you can see that AllOrigins is not working cause you'll get a CORS error.
You can see that if you open the console window in your browser (in more tools -  developer tools).
The only thing that rests then is to retry sending your question several times.

You could solve this by building your own local AllOrigins server: their Github page tells you how. But that is maybe asking too much.

So maybe we should stick to the Gemini version..........
I am going to show you how to add voice to that next time.
Till that time you really can play and have fun with this.

Till next time then.
Have fun

Luc Volders