Sure! Below is a simple web page example that lets users enter text, generate speech using the Web Speech API (SpeechSynthesis), control the speed and pitch, and export the speech as a WAV file. It also includes a share button to create a shareable URL containing the text, speed, and pitch as URL hash parameters (#/).
Shareable URL containing input text, speed and pitch in hash part (#/), which auto-loads the parameters on page load
Handles browsers that do not support SpeechSynthesis or MediaRecorder gracefully
Limitations:
Exporting speech as WAV via Web Speech API is tricky, as the Web Speech API does not provide raw audio data.
The workaround records audio output from the speech synthesis using MediaRecorder on the audio playback device.
This works only on some browsers (latest Chrome/Edge/Firefox with permissions).
For unsupported browsers, user is notified.
Code:
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 Speed & Pitch and Export WAV</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 2em auto;
padding: 1em;
}
label {
display: block;
margin-top: 1em;
}
input[type=range] {
width: 100%;
}
textarea {
width: 100%;
height: 100px;
}
button {
margin-top: 1em;
}
#status {
margin-top: 1em;
color: #555;
}
</style>
</head>
<body>
<h1>Voice Generator</h1>
<label for="text">Text to Speak:</label>
<textarea id="text" placeholder="Enter text to speak"></textarea>
<label for="speed">Speed: <span id="speedValue">1</span></label>
<input type="range" id="speed" min="0.5" max="2" step="0.1" value="1" />
<label for="pitch">Pitch: <span id="pitchValue">1</span></label>
<input type="range" id="pitch" min="0" max="2" step="0.1" value="1" />
<button id="speakBtn">Speak</button>
<button id="exportBtn">Export as WAV</button>
<button id="shareBtn">Generate Share URL</button>
<div id="status"></div>
<script>
(() => {
const textEl = document.getElementById('text');
const speedEl = document.getElementById('speed');
const pitchEl = document.getElementById('pitch');
const speedValueEl = document.getElementById('speedValue');
const pitchValueEl = document.getElementById('pitchValue');
const speakBtn = document.getElementById('speakBtn');
const exportBtn = document.getElementById('exportBtn');
const shareBtn = document.getElementById('shareBtn');
const statusEl = document.getElementById('status');
// Update display of speed/pitch values
speedEl.addEventListener('input', () => {
speedValueEl.textContent = speedEl.value;
});
pitchEl.addEventListener('input', () => {
pitchValueEl.textContent = pitchEl.value;
});
// Parse URL hash to load parameters
function loadFromHash() {
if (!location.hash.startsWith('#/')) return;
try {
const paramsStr = location.hash.slice(2);
// paramsStr expected to be URL encoded, parsing JSON encoded
const paramsJson = decodeURIComponent(paramsStr);
const params = JSON.parse(paramsJson);
if (params.text) {
textEl.value = params.text;
}
if (params.speed) speedEl.value = params.speed;
if (params.pitch) pitchEl.value = params.pitch;
speedValueEl.textContent = speedEl.value;
pitchValueEl.textContent = pitchEl.value;
} catch(e) {
console.warn('Failed to parse hash params', e);
}
}
loadFromHash();
// Save params into hash
function saveToHash() {
const params = {
text: textEl.value,
speed: speedEl.value,
pitch: pitchEl.value
};
// Encode as JSON and then URI encode to put in hash
const jsonStr = JSON.stringify(params);
location.hash = '#/' + encodeURIComponent(jsonStr);
}
// Check if Speech Synthesis is supported
const synth = window.speechSynthesis;
if (!synth) {
statusEl.textContent = 'Speech Synthesis API not supported in this browser.';
speakBtn.disabled = true;
exportBtn.disabled = true;
}
// Speak function
function speak(text, rate, pitch) {
if (synth.speaking) {
synth.cancel();
}
if (text.trim().length === 0) {
statusEl.textContent = 'Please enter text to speak.';
return;
}
const utter = new SpeechSynthesisUtterance(text);
utter.rate = +rate;
utter.pitch = +pitch;
utter.onstart = () => { statusEl.textContent = 'Speaking...'; };
utter.onend = () => { statusEl.textContent = 'Finished speaking.'; };
utter.onerror = e => { statusEl.textContent = 'Error in speech synthesis: ' + e.error; };
synth.speak(utter);
}
speakBtn.addEventListener('click', () => {
speak(textEl.value, speedEl.value, pitchEl.value);
});
// Export WAV by recording audio output while speaking
exportBtn.addEventListener('click', async () => {
if (!('MediaRecorder' in window)) {
statusEl.textContent = 'MediaRecorder API not supported in this browser.';
return;
}
if (!synth) {
statusEl.textContent = 'Speech Synthesis API not supported.';
return;
}
if (textEl.value.trim() === '') {
statusEl.textContent = 'Please enter text to speak.';
return;
}
statusEl.textContent = 'Preparing recording...';
// Create an AudioContext and a destination to capture output
const audioContext = new AudioContext();
const destination = audioContext.createMediaStreamDestination();
// Create a dummy MediaStreamAudioSourceNode (needed?)
// This implementation records whatever is outputted to speakers:
// The easiest way is to route speech synthesis audio through Web Audio API.
// Sadly, SpeechSynthesis is not exposed as audio nodes.
// Workaround: create offscreen <audio> element to play TTS audio offline? No direct way.
// Alternative approach:
// Use SpeechSynthesis + audio output capture via MediaRecorder.
// Here is the preferred approach:
// 1. Create a hidden <video> or <audio> element and feed TTS audio (no direct API for that).
// 2. Or record system audio with getDisplayMedia constraints - but that requires permission to capture screen.
// So we will try this approach:
// Use navigator.mediaDevices.getDisplayMedia({audio: true, video:false})
// and tell user to select "Chrome Tab", to capture tab audio only.
// Then play speech synthesis and record via MediaRecorder from that stream.
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
statusEl.textContent = 'getDisplayMedia API with audio capture is not supported in this browser.';
return;
}
// Ask user to share tab audio (no video)
statusEl.textContent = 'Please share your tab audio to record speech output.';
try {
const mediaStream = await navigator.mediaDevices.getDisplayMedia({ audio: true, video: false });
statusEl.textContent = 'Recording speech... Please wait and do not close the tab.';
const chunks = [];
const recorder = new MediaRecorder(mediaStream, { mimeType: 'audio/webm' });
recorder.ondataavailable = e => {
if (e.data.size > 0) chunks.push(e.data);
};
recorder.onstop = () => {
statusEl.textContent = 'Recording finished. Preparing WAV file...';
const blob = new Blob(chunks, {type: 'audio/webm'});
// Convert webm audio to WAV - no native browser API.
// We will offer the webm file directly for download, as WAV conversion requires libraries.
// Create a download link
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'speech.webm'; // Using webm extension - likely better than WAV due to complexity
a.textContent = 'Download Speech Audio';
// Remove old link if any
const oldLink = document.getElementById('downloadLink');
if (oldLink) oldLink.remove();
a.id = 'downloadLink';
a.style.display = 'block';
a.style.marginTop = '10px';
statusEl.innerHTML = '';
statusEl.appendChild(a);
mediaStream.getTracks().forEach(t => t.stop());
};
recorder.start();
// Speak after short delay to ensure recorder is started capturing
setTimeout(() => {
speak(textEl.value, speedEl.value, pitchEl.value);
// Stop recording after speech ends or max 15 seconds
let ended = false;
synth.onvoiceschanged = () => {};
const stopRecording = () => {
if (!ended) {
ended = true;
recorder.stop();
}
};
// Listen for speech synthesis end event
// (SpeechSynthesisUtterance instance `utter` used in speak() is local scope, so we recreate)
// Instead, listen for "onend" event globally:
// We'll hook into speak function to handle this.
// Recreate utter to catch events here
const utter = new SpeechSynthesisUtterance(textEl.value);
utter.rate = +speedEl.value;
utter.pitch = +pitchEl.value;
utter.onend = stopRecording;
utter.onerror = e => {
statusEl.textContent = `Error during speech synthesis: ${e.error}`;
stopRecording();
};
synth.speak(utter);
// Safety stop at 15 seconds in case event doesn't fire
setTimeout(() => {
stopRecording();
}, 15000);
}, 1000);
} catch (err) {
statusEl.textContent = 'Error capturing audio: ' + err.message;
}
});
// Share button: generate shareable URL with params in hash
shareBtn.addEventListener('click', () => {
if (textEl.value.trim() === '') {
statusEl.textContent = 'Please enter some text to share.';
return;
}
saveToHash();
navigator.clipboard.writeText(location.href).then(() => {
statusEl.textContent = 'Shareable URL copied to clipboard!';
}, () => {
statusEl.textContent = 'Failed to copy URL to clipboard. URL: ' + location.href;
});
});
})();
</script>
</body>
</html>
How to use this:
Open the HTML file in a modern browser (Chrome or Edge recommended).
Enter your text.
Adjust speed and pitch sliders.
Click Speak to hear the text.
To export, click Export as WAV:
It will ask to capture your tab audio. You must select "Chrome Tab" (or similar) and allow audio.
It will record speech output and at the end offer a download link.
Note: The exported file will be in WebM format since WAV conversion client-side is complex. Most audio players support WebM.
Click Generate Share URL to copy a URL with your text and settings encoded in the hash. Opening that URL will autofill the form.
Notes:
Exporting pure WAV files requires complex processing or a server backend. The above approach uses WebM audio, which is the best practical client-only solution currently.
Sharing works via the URL hash which encodes a JSON string of the parameters.
If your browser does not support required APIs, user-friendly messages appear.
If you want me to help make a pure WAV exporter (more complex) or use Recorder.js and upload to backend, I can assist!