The Javascript speech synthesis API works in all modern browsers:
SpeechSynthesis - Web APIs | MDN[
^]
The supported languages will vary depending on the browser. For example, on my PC, Firefox only supports English, but Chrome
(and by extension other Chromium-based browsers) supports many more languages.
Using the Web Speech API for Multilingual Translations | CSS-Tricks[
^]
If you prefer to generate the audio file on the server, you should be able to combine
the Audio API[
^] with
a Blob URL[
^] to play the file. For example:
Play audio via fetch POST request - Jignesh Kakadiya - Medium[
^]
async function speak(text, language) {
const url = "/text-to-speech/";
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: text, language: language })
};
let response = await fetch(url, requestOptions);
if (!response.ok) {
throw new Error(`${response.status}: ${response.statusText}`);
}
var reader = response.body.getReader();
var result = await reader.read();
var blob = new Blob([result.value], { type: 'audio/mp3' });
var url = window.URL.createObjectURL(blob);
window.audio = new Audio();
window.audio.src = url;
window.audio.play();
}