Haan, bilkul! Aap text ko video mein convert karte waqt voice bhi add kar sakte hain. Ye thoda advanced hai kyunki humein canvas animation ko speech synthesis ke saath sync karna hoga aur fir dono ko record karna hoga.
Browser mein client-side par audio aur video ko sahi se mux (combine) karna thoda complex hota hai, khaas kar ke ek downloadble file mein. Is example mein, hum Text-to-Speech (TTS) ko canvas animation ke saath chalayenge, aur jab user video download karega, to woh video file audio ke bina hogi. Lekin, video create hote waqt user audio ko speaker se sun sakta hai.
Niche diya gaya code dono functionalities ko integrate karta hai:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text to Video Creator with Voice</title>
<style>
/* --- General Styles --- */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', sans-serif;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
min-height: 100vh;
padding: 20px;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
text-align: center;
color: white;
margin-bottom: 30px;
font-size: 2.5em;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}
.main-content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
margin-bottom: 30px;
}
@media (max-width: 768px) {
.main-content {
grid-template-columns: 1fr;
}
}
.control-panel, .preview-panel {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.preview-panel {
display: flex;
flex-direction: column;
align-items: center;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: bold;
}
textarea {
width: 100%;
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 16px;
resize: vertical;
min-height: 100px;
}
input[type="text"],
input[type="number"],
select {
width: 100%;
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 16px;
}
input[type="color"] {
width: 60px;
height: 40px;
border: none;
border-radius: 5px;
cursor: pointer;
vertical-align: bottom; /* Align color picker better */
}
.color-inputs {
display: flex;
gap: 20px;
align-items: center;
}
.animation-options {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-top: 10px;
}
.animation-btn {
padding: 10px;
border: 2px solid #ddd;
border-radius: 8px;
background: white;
cursor: pointer;
transition: all 0.3s;
font-size: 0.9em;
}
.animation-btn:hover {
border-color: #2a5298;
background: #f0f8ff;
}
.animation-btn.active {
border-color: #2a5298;
background: #2a5298;
color: white;
}
#canvas {
border: 2px solid #ddd;
border-radius: 10px;
max-width: 100%;
background: #000;
}
.controls-section {
margin-top: 30px;
border-top: 1px solid #eee;
padding-top: 20px;
}
.controls-section h2 {
width: 100%;
text-align: center;
margin-bottom: 15px;
color: #2a5298;
}
.tts-settings {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
align-items: center;
}
.tts-settings .form-group {
margin-bottom: 0; /* Overwrite default margin */
}
.tts-settings select, .tts-settings input[type="range"] {
min-width: 120px; /* Minimum width for controls */
}
.slider-group {
display: flex;
align-items: center;
gap: 10px;
}
input[type="range"] {
flex: 1;
}
.slider-value {
min-width: 50px;
text-align: center;
font-weight: bold;
color: #2a5298;
}
.tts-status-container {
margin-top: 15px;
font-size: 0.9em;
padding: 8px;
border-radius: 5px;
grid-column: span 3; /* Occupy full width in grid */
}
.tts-status-container.speaking { background: #bee3f8; color: #2c5282;}
.tts-status-container.paused { background: #feebc8; color: #7b341e;}
.tts-status-container.ready { background: #c6f6d5; color: #276749;}
/* Button Styles */
button {
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
font-weight: bold;
display: inline-flex; /* For aligning icon and text */
align-items: center;
justify-content: center;
gap: 5px;
}
.preview-btn { background: #805ad5; color: white; }
.preview-btn:hover { background: #6b46c1; transform: translateY(-2px); }
.create-video-btn { background: #48bb78; color: white; } /* Changed from play-btn */
.create-video-btn:hover { background: #38a169; transform: translateY(-2px); }
.stop-btn { background: #f56565; color: white; }
.stop-btn:hover { background: #e53e3e; transform: translateY(-2px); }
.download-btn { background: #4299e1; color: white; }
.download-btn:hover { background: #3182ce; transform: translateY(-2px); }
.speak-btn-tts { background: #667eea; color: white; }
.speak-btn-tts:hover { background: #5a67d8; transform: translateY(-2px); }
/* Status for Video */
.status {
margin-top: 20px;
padding: 10px;
border-radius: 8px;
text-align: center;
font-weight: bold;
}
.status.ready { background: #c6f6d5; color: #276749; }
.status.recording { background: #fed7d7; color: #742a2a; }
@media (max-width: 600px) {
.tts-settings {
grid-template-columns: 1fr; /* Stack controls on smaller screens */
}
.tts-settings .form-group label,
.tts-settings .form-group select,
.tts-settings .form-group input[type="range"] {
width: 100%; /* Make controls full width */
}
.tts-settings .slider-group {
flex-direction: column;
align-items: stretch;
}
.tts-settings .slider-value {
margin-top: 5px;
}
.tts-settings button {
width: 100%; /* Full width for speak button */
}
.tts-status-container {
grid-column: span 1; /* Single column */
}
.tts-controls {
margin-top: 20px; /* Reduce top margin on small screens */
}
}
</style>
</head>
<body>
<div class="container">
<h1>🎬 Text to Video Creator with Voice 🎤</h1>
<div class="main-content">
<div class="control-panel">
<h2 style="margin-bottom: 20px; color: #2a5298;">Video Settings</h2>
<div class="form-group">
<label for="text">Enter Your Text:</label>
<textarea id="text" placeholder="Type your text here...">Hello! This is a text to video demonstration with voice.</textarea>
</div>
<div class="form-group">
<label for="fontSize">Font Size:</label>
<div class="slider-group">
<input type="range" id="fontSize" min="20" max="100" value="40">
<span class="slider-value" id="fontSizeValue">40</span>
</div>
</div>
<div class="form-group">
<label for="fontFamily">Font Style:</label>
<select id="fontFamily">
<option value="Arial">Arial</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New">Courier New</option>
<option value="Georgia">Georgia</option>
<option value="Verdana">Verdana</option>
<option value="Impact">Impact</option>
</select>
</div>
<div class="form-group">
<label>Colors:</label>
<div class="color-inputs">
<div>
<label>Text Color:</label>
<input type="color" id="textColor" value="#ffffff">
</div>
<div>
<label>Background:</label>
<input type="color" id="bgColor" value="#000000">
</div>
</div>
</div>
<div class="form-group">
<label>Animation Style:</label>
<div class="animation-options">
<button class="animation-btn active" data-animation="typewriter">Typewriter</button>
<button class="animation-btn" data-animation="fade">Fade In</button>
<button class="animation-btn" data-animation="slide">Slide In</button>
<button class="animation-btn" data-animation="zoom">Zoom In</button>
<button class="animation-btn" data-animation="bounce">Bounce</button>
<button class="animation-btn" data-animation="rotate">Rotate</button>
</div>
</div>
<div class="form-group">
<label for="duration">Animation Duration (seconds):</label>
<div class="slider-group">
<input type="range" id="duration" min="1" max="10" value="3" step="0.5">
<span class="slider-value" id="durationValue">3</span>
</div>
</div>
<!-- TTS Controls Section -->
<div class="controls-section tts-controls">
<h2 style="margin-bottom: 10px;">Voice Settings</h2>
<div class="tts-settings">
<div class="form-group">
<label for="voiceSelect">Voice:</label>
<select id="voiceSelect"></select>
</div>
<div class="form-group">
<label for="rate">Speed:</label>
<div class="slider-group">
<input type="range" id="rate" min="0.1" max="2" value="1" step="0.1">
<span class="slider-value" id="rateValue">1</span>
</div>
</div>
<div class="form-group">
<label for="pitch">Pitch:</label>
<div class="slider-group">
<input type="range" id="pitch" min="0" max="2" value="1" step="0.1">
<span class="slider-value" id="pitchValue">1</span>
</div>
</div>
<div class="form-group">
<label for="volume">Volume:</label>
<div class="slider-group">
<input type="range" id="volume" min="0" max="1" value="1" step="0.1">
<span class="slider-value" id="volumeValue">1</span>
</div>
</div>
<!-- Spacer to align button -->
<div style="grid-column: span 2;"></div>
<button class="speak-btn-tts" onclick="speakTTS()">🔊 Speak Text</button>
</div>
<div class="tts-status-container ready" id="ttsStatus">Ready</div>
</div>
</div>
<div class="preview-panel">
<h2 style="margin-bottom: 20px; color: #2a5298;">Preview & Create</h2>
<canvas id="canvas" width="640" height="360"></canvas>
<div class="controls-section">
<button class="preview-btn" onclick="preview()">👁️ Preview</button>
<button class="create-video-btn" onclick="startRecording()">🎥 Create Video</button>
<button class="stop-btn" onclick="stopRecording()">⏹️ Stop</button>
<button class="download-btn" onclick="downloadVideo()" id="downloadBtn" style="display: none;">💾 Download Video (No Audio)</button>
</div>
<div class="status ready" id="status">Ready</div>
</div>
</div>
</div>
<script>
// --- Text-to-Speech (TTS) Core Logic ---
const synth = window.speechSynthesis;
let voices = [];
let currentUtterance = null;
let isSpeakingTTS = false;
// TTS DOM Elements
const voiceSelect = document.getElementById('voiceSelect');
const rateInput = document.getElementById('rate');
const pitchInput = document.getElementById('pitch');
const volumeInput = document.getElementById('volume');
const rateValue = document.getElementById('rateValue');
const pitchValue = document.getElementById('pitchValue');
const volumeValue = document.getElementById('volumeValue');
const ttsStatus = document.getElementById('ttsStatus');
function loadVoices() {
voices = synth.getVoices();
voiceSelect.innerHTML = '';
// Sort voices alphabetically by name for better usability
voices.sort((a, b) => a.name.localeCompare(b.name));
voices.forEach((voice, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = `${voice.name} (${voice.lang})`;
voiceSelect.appendChild(option);
});
}
function updateTTSSliderValues() {
rateValue.textContent = rateInput.value;
pitchValue.textContent = pitchInput.value;
volumeValue.textContent = volumeInput.value;
}
function updateTTSStatus(message, className) {
ttsStatus.textContent = message;
ttsStatus.className = `tts-status-container ${className}`;
}
function speakTTS() {
if (synth.speaking) {
console.error('Already speaking...');
return;
}
const text = document.getElementById('text').value;
if (text.trim() === '') {
updateTTSStatus("Please enter text to speak.", "paused");
return;
}
currentUtterance = new SpeechSynthesisUtterance(text);
// Set voice
if (voices.length > 0 && voiceSelect.value) {
currentUtterance.voice = voices[voiceSelect.value];
} else if (voices.length > 0) {
// If no voice selected, try to pick a default or first available
currentUtterance.voice = voices[0];
} else {
updateTTSStatus("No voices available. Check browser support or try again.", "paused");
return;
}
// Set properties
currentUtterance.rate = parseFloat(rateInput.value);
currentUtterance.pitch = parseFloat(pitchInput.value);
currentUtterance.volume = parseFloat(volumeInput.value);
// TTS Event Listeners
currentUtterance.onstart = () => {
updateTTSStatus('Speaking...', 'speaking');
isSpeakingTTS = true;
};
currentUtterance.onend = () => {
updateTTSStatus('Ready', 'ready');
isSpeakingTTS = false;
// If TTS finished naturally and we are NOT recording, clear the utterance object
if (!isRecordingVideo) {
currentUtterance = null;
}
};
currentUtterance.onerror = (event) => {
console.error('SpeechSynthesisUtterance Error:', event);
updateTTSStatus('Error speaking.', 'paused');
isSpeakingTTS = false;
currentUtterance = null;
};
synth.speak(currentUtterance);
}
function stopTTS() {
if (synth.speaking || synth.paused) {
synth.cancel();
updateTTSStatus('Stopped', 'ready');
isSpeakingTTS = false;
currentUtterance = null;
}
}
// --- Video Canvas Animation Logic ---
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const videoStatus = document.getElementById('status');
const downloadBtn = document.getElementById('downloadBtn');
let mediaRecorder;
let recordedChunks = [];
let animationId = null; // Variable to hold animation frame request ID
let isRecordingVideo = false;
let currentAnimation = 'typewriter';
function getSettings() {
return {
text: document.getElementById('text').value,
fontSize: parseInt(document.getElementById('fontSize').value),
fontFamily: document.getElementById('fontFamily').value,
textColor: document.getElementById('textColor').value,
bgColor: document.getElementById('bgColor').value,
duration: parseFloat(document.getElementById('duration').value) * 1000 // Convert seconds to milliseconds
};
}
function clearCanvas(bgColor) {
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// --- Individual Animation Functions ---
function typewriterAnimation(settings, progress) {
const textLength = Math.floor(settings.text.length * progress);
const displayText = settings.text.substring(0, textLength);
clearCanvas(settings.bgColor);
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(displayText, canvas.width / 2, canvas.height / 2);
}
function fadeAnimation(settings, progress) {
clearCanvas(settings.bgColor);
ctx.globalAlpha = progress; // Control transparency
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(settings.text, canvas.width / 2, canvas.height / 2);
ctx.globalAlpha = 1; // Reset alpha
}
function slideAnimation(settings, progress) {
clearCanvas(settings.bgColor);
// Text starts off-screen left and slides in
const x = -canvas.width + (canvas.width * 2 * progress);
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(settings.text, x, canvas.height / 2);
}
function zoomAnimation(settings, progress) {
clearCanvas(settings.bgColor);
const scale = progress; // Scale grows from 0 to 1
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2); // Move origin to center
ctx.scale(scale, scale);
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(settings.text, 0, 0); // Draw at the new origin
ctx.restore(); // Restore original canvas state
}
function bounceAnimation(settings, progress) {
clearCanvas(settings.bgColor);
const bounceHeight = 50; // How high the text bounces
const bounceFrequency = 3; // Number of bounces
// Use sine wave to simulate bounce
const bounce = Math.abs(Math.sin(progress * Math.PI * bounceFrequency));
const y = canvas.height / 2 - (bounce * bounceHeight);
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(settings.text, canvas.width / 2, y);
}
function rotateAnimation(settings, progress) {
clearCanvas(settings.bgColor);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2); // Move origin to center
ctx.rotate(progress * Math.PI * 2); // Rotate by 2 PI radians (a full circle)
ctx.fillStyle = settings.textColor;
ctx.font = `${settings.fontSize}px ${settings.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(settings.text, 0, 0);
ctx.restore();
}
// Main animation dispatcher
function animate(settings, progress) {
switch(currentAnimation) {
case 'typewriter':
typewriterAnimation(settings, progress);
break;
case 'fade':
fadeAnimation(settings, progress);
break;
case 'slide':
slideAnimation(settings, progress);
break;
case 'zoom':
zoomAnimation(settings, progress);
break;
case 'bounce':
bounceAnimation(settings, progress);
break;
case 'rotate':
rotateAnimation(settings, progress);
break;
}
}
// --- Control Functions ---
function preview() {
// Clear any ongoing animation
if (animationId) {
cancelAnimationFrame(animationId);
}
stopTTS(); // Ensure any previous TTS is stopped for a clean preview
const settings = getSettings();
const startTime = Date.now();
speakTTS(); // Start TTS for preview
function drawFrame() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / settings.duration, 1); // Progress from 0 to 1
animate(settings, progress);
if (progress < 1) {
animationId = requestAnimationFrame(drawFrame);
} else {
// Animation finished. If TTS is still speaking, stop it.
if (isSpeakingTTS) {
synth.cancel();
updateTTSStatus('Preview finished. TTS stopped.', 'ready');
isSpeakingTTS = false;
}
}
}
drawFrame(); // Start the animation loop
}
function startRecording() {
if (isRecordingVideo) return; // Prevent multiple recordings
stopTTS(); // Stop any previous TTS playback
if (animationId) {
cancelAnimationFrame(animationId); // Stop any preview animation
}
recordedChunks = []; // Reset recorded data
// Capture stream from canvas
const stream = canvas.captureStream(30); // Capture at 30 FPS
// Initialize MediaRecorder
mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm' // WebM format is common for canvas recording
});
// Event handler for data chunks
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
recordedChunks.push(event.data);
}
};
// Event handler when recording stops
mediaRecorder.onstop = () => {
const blob = new Blob(recordedChunks, {
type: 'video/webm'
});
const url = URL.createObjectURL(blob);
// Show download button
downloadBtn.style.display = 'inline-flex'; // Changed to inline-flex for button styling
downloadBtn.onclick = () => {
const a = document.createElement('a');
a.href = url;
a.download = 'text-animation.webm'; // Default filename
a.click();
URL.revokeObjectURL(url); // Clean up the object URL
};
videoStatus.textContent = 'Video creation complete! Click download to save.';
videoStatus.className = 'status ready';
isRecordingVideo = false;
stopTTS(); // Ensure TTS is stopped when recording stops
downloadBtn.disabled = false; // Enable download button
};
// Event handler for MediaRecorder errors
mediaRecorder.onerror = (event) => {
console.error("MediaRecorder Error:", event);
videoStatus.textContent = 'Error during video recording.';
videoStatus.className = 'status ready';
isRecordingVideo = false;
stopTTS();
};
mediaRecorder.start(); // Start the recording
isRecordingVideo = true;
videoStatus.textContent = 'Recording video...';
videoStatus.className = 'status recording';
downloadBtn.disabled = true; // Disable download until recording is finished
// Start TTS and the animation loop for recording
speakTTS();
const settings = getSettings();
const startTime = Date.now();
function recordFrame() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / settings.duration, 1);
animate(settings, progress);
if (progress < 1 && isRecordingVideo) {
// Continue recording and animating
requestAnimationFrame(recordFrame);
} else {
// Animation finished, stop recording
stopRecording();
}
}
recordFrame(); // Start the recording animation loop
}
function stopRecording() {
// Stop MediaRecorder if it's active
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
// Stop animation frame request
if (animationId) {
cancelAnimationFrame(animationId);
}
// Stop TTS
stopTTS();
isRecordingVideo = false;
// Status and button states are handled in mediaRecorder.onstop
}
// --- Initialization and Event Listeners ---
// Update slider values display on input
rateInput.addEventListener('input', updateTTSSliderValues);
pitchInput.addEventListener('input', updateTTSSliderValues);
volumeInput.addEventListener('input', updateTTSSliderValues);
// Update selected animation style
document.querySelectorAll('.animation-btn').forEach(btn => {
btn.addEventListener('click', function() {
// Remove active class from all buttons
document.querySelectorAll('.animation-btn').forEach(b => b.classList.remove('active'));
// Add active class to the clicked button
this.classList.add('active');
currentAnimation = this.dataset.animation; // Update current animation
});
});
// Load voices when the SpeechSynthesis API is ready
if (synth.onvoiceschanged !== undefined) {
synth.onvoiceschanged = loadVoices;
} else {
// Fallback for browsers that don't support onvoiceschanged
loadVoices();
}
// Initial canvas setup: clear canvas with background color
clearCanvas('#000000');
updateTTSSliderValues(); // Display initial slider values
updateTTSStatus('Ready', 'ready'); // Set initial TTS status
// --- Browser Support Checks ---
if (!('speechSynthesis' in window)) {
console.warn('Speech Synthesis not supported in this browser.');
// Inform user if TTS is not supported
document.querySelector('.tts-controls').innerHTML = '<p style="color: red; text-align: center; font-weight: bold;">Your browser does not support Text-to-Speech.</p>';
}
if (!('MediaRecorder' in window)) {
console.warn('MediaRecorder not supported in this browser.');
// Inform user if video recording is not supported
videoStatus.textContent = 'Your browser does not support Media Recording.';
videoStatus.className = 'status ready';
// Disable video creation buttons
document.querySelector('.create-video-btn').disabled = true;
document.querySelector('.preview-btn').disabled = true;
}
</script>
</body>
</html>
Key Changes:
- TTS Functionality Integrated: The core logic for Text-to-Speech (using
window.speechSynthesis) from the previous example has been merged.
- TTS Controls:
- Voice selection dropdown (
<select id="voiceSelect">).
- Rate, Pitch, Volume sliders with their value displays.
- A "Speak Text" button (
.speak-btn-tts) to test the voice independently.
- A status area (
#ttsStatus) to show TTS feedback.
- Synchronization:
preview() function: Now calls speakTTS() to play the voice alongside the animation preview. It also stops the TTS when the preview animation finishes.
startRecording() function: Calls speakTTS() to start the voice generation. This voice will play through the user's speakers. Simultaneously, it captures the canvas animation using MediaRecorder.
stopRecording() function: Explicitly calls stopTTS() to ensure the synthesized voice stops when the video recording is stopped.
- Download Button: The download button (
#downloadBtn) now has the text "Download Video (No Audio)". This is because the browser's MediaRecorder captures the canvas stream but doesn't automatically mux the separate TTS audio stream into the output video file.
- UI & Styling: Added sections and styles for the new TTS controls.
- Browser Compatibility: Added checks for browser support for both
speechSynthesis and MediaRecorder.
How to Use:
- Enter your text.
- Adjust video settings (font, colors, animation, duration).
- Adjust voice settings (voice, speed, pitch, volume).
- Click "Preview": You'll hear the text spoken and see the animation.
- Click "Create Video": The text will be animated on the canvas, and the voice will play. The canvas content is recorded simultaneously.
- Click "Stop" anytime to halt both video recording and voice playback.
- Once recording stops (either manually or when animation finishes), the "Download Video (No Audio)" button will appear. Click it to save the animated video file (in WebM format).
Remember, the downloaded video file will only contain the animation, not the voice. The voice was played live during the creation process.