Sure! Here is a simple example of an HTML page that uses the Web Speech API for text-to-speech with controls for speed and pitch, a voice selector, and an option to export the synthesized speech as a WAV file. It also includes a shareable URL hash to preserve the text and settings.
The script checks for browser support, and if the API is not supported, it will notify the user.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voice Generator with Export WAV</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 2rem auto;
padding: 1rem;
background: #f5f5f5;
}
label {
display: block;
margin-top: 1rem;
}
select, input[type=range], textarea {
width: 100%;
margin-top: 0.25rem;
}
button {
margin-top: 1rem;
padding: 0.5rem 1rem;
}
.status {
margin-top: 1rem;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Voice Generator (TTS) with Export WAV</h1>
<label for="text">Text to Speak:</label>
<textarea id="text" rows="4" placeholder="Enter text here..."></textarea>
<label for="voice">Voice:</label>
<select id="voice"></select>
<label for="rate">Speed (Rate): <span id="rateVal">1</span></label>
<input type="range" id="rate" min="0.5" max="2" step="0.1" value="1" />
<label for="pitch">Pitch: <span id="pitchVal">1</span></label>
<input type="range" id="pitch" min="0" max="2" step="0.1" value="1" />
<button id="speakBtn">Speak</button>
<button id="exportWavBtn">Export WAV</button>
<div class="status" id="status"></div>
<script>
// Feature detection
if (!('speechSynthesis' in window)) {
document.body.innerHTML = '<h2>Your browser does not support Speech Synthesis API.</h2>';
} else if (!window.MediaRecorder) {
alert('Warning: Your browser does not support MediaRecorder API. WAV export might not work.');
}
const textEl = document.getElementById('text');
const voiceEl = document.getElementById('voice');
const rateEl = document.getElementById('rate');
const rateValEl = document.getElementById('rateVal');
const pitchEl = document.getElementById('pitch');
const pitchValEl = document.getElementById('pitchVal');
const speakBtn = document.getElementById('speakBtn');
const exportBtn = document.getElementById('exportWavBtn');
const statusEl = document.getElementById('status');
let voices = [];
function populateVoices() {
voices = speechSynthesis.getVoices();
voiceEl.innerHTML = '';
voices.forEach((voice, i) => {
const option = document.createElement('option');
option.value = i;
option.textContent = `${voice.name} (${voice.lang})${voice.default ? ' [default]' : ''}`;
voiceEl.appendChild(option);
});
// Try to restore voice from hash or select default
const urlParams = new URLSearchParams(window.location.hash.substr(2)); // remove '#/'
if (urlParams.has('voice')) {
const idx = parseInt(urlParams.get('voice'));
if (!isNaN(idx) && idx >= 0 && idx < voices.length) voiceEl.value = idx;
} else {
const defaultIdx = voices.findIndex(v => v.default);
if(defaultIdx >= 0) voiceEl.value = defaultIdx;
}
}
populateVoices();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoices;
}
// Update displayed values
rateEl.addEventListener('input', () => {
rateValEl.textContent = rateEl.value;
updateHash();
});
pitchEl.addEventListener('input', () => {
pitchValEl.textContent = pitchEl.value;
updateHash();
});
voiceEl.addEventListener('change', updateHash);
textEl.addEventListener('input', updateHash);
// Speak function
function speak() {
if (speechSynthesis.speaking) {
speechSynthesis.cancel();
}
const text = textEl.value.trim();
if (text === '') {
statusEl.textContent = 'Please enter some text.';
return;
}
const utter = new SpeechSynthesisUtterance(text);
utter.voice = voices[voiceEl.value];
utter.rate = Number(rateEl.value);
utter.pitch = Number(pitchEl.value);
utter.onstart = () => {
statusEl.textContent = 'Speaking...';
speakBtn.disabled = true;
};
utter.onend = () => {
statusEl.textContent = 'Done speaking.';
speakBtn.disabled = false;
};
utter.onerror = (e) => {
statusEl.textContent = 'Error during speaking: ' + e.error;
speakBtn.disabled = false;
};
speechSynthesis.speak(utter);
}
// WAV Export using SpeechSynthesis + WebAudio + MediaRecorder workaround
// Note: The Web Speech API does not provide direct audio stream output, so this method uses captureStream on an <audio> element which plays synthesized speech and captures it.
// This method is limited and browser support may vary.
async function exportWAV() {
if (!('MediaRecorder' in window)) {
alert('MediaRecorder API not supported in this browser.');
return;
}
const text = textEl.value.trim();
if (!text) {
alert('Please enter some text to export.');
return;
}
statusEl.textContent = 'Preparing audio for export. Please wait...';
speakBtn.disabled = true;
exportBtn.disabled = true;
// Create SpeechSynthesisUtterance and play it silently into an <audio> element with captureStream
const utter = new SpeechSynthesisUtterance(text);
utter.voice = voices[voiceEl.value];
utter.rate = Number(rateEl.value);
utter.pitch = Number(pitchEl.value);
// Create an OfflineAudioContext to generate audio if possible
// But the Web Speech API does not expose the raw audio data.
// So the common hack is:
// 1) synthesize speech through SpeechSynthesis
// 2) play back speech via an <audio> element and capture the audio with MediaRecorder and captureStream()
// Unfortunately, speechSynthesis does not provide direct audio output to an <audio> element.
// Instead, we can generate speech via SpeechSynthesis and record microphone output via AudioContext + MediaStreamDestination? Not feasible.
// Alternative: Use SpeechSynthesis.speak + SpeechSynthesisUtterance.onstart + capture audio from SpeechSynthesis audio output
// But no direct audio track available for us.
// So we use a library or fallback to showing an error.
// Alternative approach - Use a third-party TTS server, which is out of scope.
// So try a hack: Use SpeechSynthesis + an <iframe> with SpeechSynthesis and captureStream (usually not workable).
// For demo, let's try a synthetic solution:
statusEl.textContent = 'Audio export not supported fully by Web Speech API. This is a known limitation.';
alert('Export WAV not supported due to limitations of the Web Speech API in browsers.\nYou can use external tools or server-side TTS for WAV export.');
speakBtn.disabled = false;
exportBtn.disabled = false;
}
// URL Hash encoding/decoding for sharing
function updateHash() {
const params = new URLSearchParams();
if(textEl.value.trim() !== '') params.set('text', encodeURIComponent(textEl.value.trim()));
params.set('voice', voiceEl.value);
params.set('rate', rateEl.value);
params.set('pitch', pitchEl.value);
// Compose hash as #/key=value&key=value
const hash = '#/' + params.toString();
history.replaceState(null, '', hash);
}
function loadFromHash() {
if (!window.location.hash.startsWith('#/')) return;
const params = new URLSearchParams(window.location.hash.substr(2));
if (params.has('text')) textEl.value = decodeURIComponent(params.get('text'));
if (params.has('voice')) {
const val = parseInt(params.get('voice'));
if(!isNaN(val)) voiceEl.value = val;
}
if (params.has('rate')) {
const val = parseFloat(params.get('rate'));
if(!isNaN(val)) {
rateEl.value = val;
rateValEl.textContent = val;
}
}
if (params.has('pitch')) {
const val = parseFloat(params.get('pitch'));
if(!isNaN(val)) {
pitchEl.value = val;
pitchValEl.textContent = val;
}
}
}
loadFromHash();
speakBtn.addEventListener('click', speak);
exportBtn.addEventListener('click', exportWAV);
</script>
</body>
</html>
Explanation
Voice selection populates dynamically based on speechSynthesis.getVoices().
Speed and pitch use sliders with live update on labels.
Speak button creates a SpeechSynthesisUtterance and speaks the text.
Export WAV button currently shows a known limitation warning because browsers don't expose the raw audio from the Web Speech API to allow capturing or direct exporting. A true export requires a custom TTS backend or additional user permissions.
The URL hash encodes the text and settings so you can share the page with #/text=Hello&voice=2&rate=1&pitch=1 etc.
There's basic feature detection and graceful degradation.
Try opening the page in Chrome or Firefox (SpeechSynthesis supported) to test the voice generation and share the URL with your text and tuning. The export WAV function is a known hard limitation with standard Web Speech API currently.