Sure! Below is a complete example of a simple web-based voice generator that allows you to:
Enter text
Adjust speech speed (rate)
Adjust speech pitch
Play the speech via Web Speech API's SpeechSynthesis
Export the generated speech as a WAV file (using the Web Audio API)
Share the generated WAV via a link (using the Web Share API if supported)
Fall back gracefully if any features are not supported
The app's URL hash changes to #/ to indicate its state (you can expand that for routing if needed).
Important notes:
Directly exporting WAV from the Web Speech API is not supported natively because SpeechSynthesis outputs audio to speakers, not to a buffer.
To export the speech, we need to use a third-party Text-to-Speech API or perform offline synthesis with a custom voice model or use a workaround:
A common workaround is to use the SpeechSynthesis API and capture the audio output using the Web Audio API, but browsers do not allow capturing audio playback by default without user interaction.
Another approach is to use the MediaRecorder API on the AudioContext output if we feed text generated audio into it.
For simplicity, the example below uses the browser's TTS for playback, and also demonstrates generating WAV data by synthesizing audio from the SpeechSynthesisUtterance using offline methods via a method like third-party TTS (here simulated).
Full Example
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, Export WAV & Share</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
max-width: 600px;
}
label {
display: block;
margin-top: 15px;
}
input[type=range] {
width: 100%;
}
button {
margin-top: 20px;
font-size: 16px;
padding: 10px;
}
.status {
margin-top: 10px;
font-size: 14px;
}
#shareBtn {
margin-left: 10px;
}
</style>
</head>
<body>
<h1>Voice Generator</h1>
<label for="text">Text to speak:</label>
<textarea id="text" rows="4" style="width: 100%"></textarea>
<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" />
<div>
<button id="speakBtn">Speak</button>
<button id="exportBtn">Export WAV</button>
<button id="shareBtn" style="display:none;">Share WAV</button>
</div>
<div class="status" id="status"></div>
<script>
// URL hash set to "#/" on load
if (location.hash !== "#/") {
location.hash = "#/";
}
const textInput = document.getElementById("text");
const rateInput = document.getElementById("rate");
const pitchInput = document.getElementById("pitch");
const rateVal = document.getElementById("rateVal");
const pitchVal = document.getElementById("pitchVal");
const speakBtn = document.getElementById("speakBtn");
const exportBtn = document.getElementById("exportBtn");
const shareBtn = document.getElementById("shareBtn");
const status = document.getElementById("status");
rateInput.oninput = () => {
rateVal.textContent = rateInput.value;
};
pitchInput.oninput = () => {
pitchVal.textContent = pitchInput.value;
};
// Check for SpeechSynthesis support
function isSpeechSynthesisSupported() {
return 'speechSynthesis' in window && 'SpeechSynthesisUtterance' in window;
}
// Speak text
speakBtn.onclick = () => {
const text = textInput.value.trim();
if (!text) {
status.textContent = "Please enter text to speak.";
return;
}
if (!isSpeechSynthesisSupported()) {
status.textContent = "SpeechSynthesis API is not supported in your browser.";
return;
}
status.textContent = "Speaking...";
window.speechSynthesis.cancel(); // Cancel any previous speech
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = parseFloat(rateInput.value);
utterance.pitch = parseFloat(pitchInput.value);
utterance.onend = () => {
status.textContent = "Speech finished.";
};
utterance.onerror = (e) => {
status.textContent = "Error during speech: " + e.error;
};
window.speechSynthesis.speak(utterance);
};
// ===== Export WAV logic =====
// Since speechSynthesis cannot export audio directly, we must synthesize audio ourselves.
// For a demo, use Web Audio API to generate speech with OfflineAudioContext using SpeechSynthesis (not possible),
// so instead we create an AudioContext and use a third party API or text-to-speech server
// Here we simulate various approaches:
//
// For the demo, we will use a library called meSpeak.js or SpeechSynthesis with audio capture which is complex to implement
// within this snippet. Instead, we will try using SpeechSynthesis and record audio output with MediaStreamAudioDestinationNode,
// but it is limited and browser-dependent.
//
// So as a fallback, we will export silence WAV that can be replaced by user with a real TTS server.
// Helper function - create simple WAV header and buffer from Float32Array
function encodeWAV(samples, sampleRate) {
const buffer = new ArrayBuffer(44 + samples.length * 2);
const view = new DataView(buffer);
function writeString(view, offset, string) {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
/* RIFF identifier */
writeString(view, 0, 'RIFF');
/* file length */
view.setUint32(4, 36 + samples.length * 2, true);
/* RIFF type */
writeString(view, 8, 'WAVE');
/* format chunk identifier */
writeString(view, 12, 'fmt ');
/* format chunk length */
view.setUint32(16, 16, true);
/* sample format (raw) */
view.setUint16(20, 1, true);
/* channel count */
view.setUint16(22, 1, true);
/* sample rate */
view.setUint32(24, sampleRate, true);
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * 2, true);
/* block align (channel count * bytes per sample) */
view.setUint16(32, 2, true);
/* bits per sample */
view.setUint16(34, 16, true);
/* data chunk identifier */
writeString(view, 36, 'data');
/* data chunk length */
view.setUint32(40, samples.length * 2, true);
// Write samples
let offset = 44;
for (let i = 0; i < samples.length; i++, offset += 2) {
// Clamp and convert float sample to 16-bit signed integer
let s = Math.max(-1, Math.min(1, samples[i]));
s = s < 0 ? s * 0x8000 : s * 0x7FFF;
view.setInt16(offset, s, true);
}
return new Blob([view], { type: 'audio/wav' });
}
// Since generating real speech audio from text is complex,
// let's capture system audio via Web Audio API (only works with microphone or fetch audio)
// So as a demo, we generate a sine wave with pitch and speed simulating voice
function generateDummyVoiceWAV(rate, pitch, duration=2) {
// Creates a 2 seconds sine wave modulated by rate and pitch
const sampleRate = 44100;
const length = sampleRate * duration;
const samples = new Float32Array(length);
// frequency base around 220Hz (A3) modified by pitch and rate
const baseFreq = 220 * pitch;
for (let i = 0; i < length; i++) {
samples[i] = Math.sin(2 * Math.PI * baseFreq * i / sampleRate) * 0.3;
}
return encodeWAV(samples, sampleRate);
}
// More advanced real solution:
// You would need a server-side TTS API (Google, Azure, Amazon etc) or a WASM TTS engine
// to convert text => audio buffer and then export WAV.
exportBtn.onclick = () => {
const text = textInput.value.trim();
if (!text) {
status.textContent = "Enter text to export WAV.";
return;
}
status.textContent = "Generating WAV...";
// Here we just generate dummy WAV for demo
// In production: fetch from TTS server or implement offline TTS model
setTimeout(() => {
const wavBlob = generateDummyVoiceWAV(parseFloat(rateInput.value), parseFloat(pitchInput.value));
// Create download link
const url = URL.createObjectURL(wavBlob);
// create a temporary anchor for download
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = "voice.wav";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
status.textContent = "WAV exported!";
// Enable share button if possible
if (navigator.canShare && navigator.canShare({ files: [new File([wavBlob], "voice.wav", {type: "audio/wav"})] })) {
shareBtn.style.display = "inline-block";
shareBtn.disabled = false;
shareBtn.wavFile = new File([wavBlob], "voice.wav", {type: "audio/wav"});
} else {
shareBtn.style.display = "none";
}
// revoke url after sometime
setTimeout(() => URL.revokeObjectURL(url), 60000);
}, 1000);
};
shareBtn.onclick = async () => {
if (!shareBtn.wavFile) {
status.textContent = "No WAV file to share.";
return;
}
if (!navigator.canShare) {
status.textContent = "Web Share API is not supported.";
return;
}
const filesArray = [shareBtn.wavFile];
try {
await navigator.share({
files: filesArray,
title: 'Voice WAV',
text: 'Sharing generated voice WAV file.'
});
status.textContent = "Shared successfully.";
} catch (err) {
status.textContent = "Sharing failed: " + err;
}
};
</script>
</body>
</html>
How this works:
The Speak button uses SpeechSynthesis to read the text aloud with chosen speed & pitch.
The Export WAV button currently generates a dummy sine wave.wav file as a placeholder (because exporting real TTS audio is complex).
When you click Export WAV, it triggers a WAV file download.
If your browser supports Web Share API and sharing files, the Share WAV button appears allowing to share the .wav file.
The URL hash is set to #/ on page load.
Recommendations for production:
Use real TTS service with server-side generation or WASM text-to-speech engines to generate accurate speech buffers.
Capture actual SpeechSynthesis audio is complex and limited on browsers.
Consider libraries like meSpeak.js or TTS APIs like Amazon Polly, Google Cloud TTS, or Azure Cognitive Services.
Add voice selection dropdown if needed.
If you want, I can help you expand with a real TTS API integration or more advanced exporting options! Let me know.