help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
speech-recognition
/
js
RSK World
speech-recognition
Speech Recognition Dataset - Audio AI + Speech-to-Text + Voice Recognition
js
  • script.js44 KB
.gitkeepscript.js
js/script.js
Raw Download
Find: Go to:
/**
 * ============================================================================
 * Speech Recognition Dataset - JavaScript
 * ============================================================================
 * 
 * Project: Speech Recognition Dataset
 * Description: Audio speech recognition dataset with labeled speech samples 
 *              for training speech-to-text and voice recognition models.
 * 
 * ============================================================================
 * DEVELOPER INFORMATION
 * ============================================================================
 * Website: https://rskworld.in
 * Founded by: Molla Samser
 * Designer & Tester: Rima Khatun
 * Email: help@rskworld.in
 * Support: support@rskworld.in
 * Phone: +91 93305 39277
 * Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
 * 
 * ============================================================================
 * COPYRIGHT NOTICE
 * ============================================================================
 * Ā© 2026 RSK World. All rights reserved.
 * This dataset is provided for educational and research purposes.
 * 
 * ============================================================================
 */

// ============================================================================
// PRELOADER
// ============================================================================
window.addEventListener('load', () => {
    const preloader = document.getElementById('preloader');
    if (preloader) {
        setTimeout(() => {
            preloader.classList.add('hidden');
        }, 1500);
    }
});

// ============================================================================
// CUSTOM CURSOR
// ============================================================================
const cursor = document.getElementById('cursor');
const cursorFollower = document.getElementById('cursorFollower');

if (cursor && cursorFollower) {
    document.addEventListener('mousemove', (e) => {
        cursor.style.left = e.clientX + 'px';
        cursor.style.top = e.clientY + 'px';
        
        setTimeout(() => {
            cursorFollower.style.left = e.clientX - 15 + 'px';
            cursorFollower.style.top = e.clientY - 15 + 'px';
        }, 50);
    });

    // Add hover effect to interactive elements
    const interactiveElements = document.querySelectorAll('a, button, input, .feature-card, .sample-card, .use-case-card');
    interactiveElements.forEach(el => {
        el.addEventListener('mouseenter', () => cursorFollower.classList.add('hover'));
        el.addEventListener('mouseleave', () => cursorFollower.classList.remove('hover'));
    });
}

// ============================================================================
// THEME TOGGLE
// ============================================================================
const themeToggle = document.getElementById('themeToggle');
const html = document.documentElement;

// Check for saved theme preference
const savedTheme = localStorage.getItem('theme') || 'dark';
html.setAttribute('data-theme', savedTheme);
updateThemeIcon(savedTheme);

if (themeToggle) {
    themeToggle.addEventListener('click', () => {
        const currentTheme = html.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        html.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        updateThemeIcon(newTheme);
        
        showToast(`Theme changed to ${newTheme} mode`);
    });
}

function updateThemeIcon(theme) {
    if (themeToggle) {
        const icon = themeToggle.querySelector('i');
        icon.className = theme === 'dark' ? 'fas fa-moon' : 'fas fa-sun';
    }
}

// ============================================================================
// SEARCH FUNCTIONALITY
// ============================================================================
const searchBtn = document.getElementById('searchBtn');
const searchModal = document.getElementById('searchModal');
const searchInput = document.getElementById('searchInput');
const closeSearch = document.getElementById('closeSearch');
const searchResults = document.getElementById('searchResults');

const searchData = [
    { title: 'MFCC Features', section: '#features', description: 'Mel-frequency cepstral coefficients extraction' },
    { title: 'Librosa Integration', section: '#code', description: 'Audio processing with Librosa library' },
    { title: 'LSTM Model', section: '#tensorflow', description: 'Recurrent neural network for sequence modeling' },
    { title: 'PyTorch Training', section: '#pytorch', description: 'Deep learning with PyTorch framework' },
    { title: 'Audio Samples', section: '#samples', description: 'Preview dataset audio recordings' },
    { title: 'Speaker Distribution', section: '#statistics', description: 'Dataset statistics and metrics' },
    { title: 'Download Dataset', section: '#download', description: 'Get the complete dataset package' },
    { title: 'Voice Assistants', section: '#use-cases', description: 'Build intelligent voice-activated systems' },
    { title: 'Transcription', section: '#use-cases', description: 'Automatic speech-to-text conversion' },
    { title: 'FAQ', section: '#faq', description: 'Frequently asked questions' }
];

if (searchBtn && searchModal) {
    searchBtn.addEventListener('click', () => {
        searchModal.classList.add('active');
        searchInput.focus();
    });

    closeSearch.addEventListener('click', () => {
        searchModal.classList.remove('active');
    });

    searchModal.addEventListener('click', (e) => {
        if (e.target === searchModal) {
            searchModal.classList.remove('active');
        }
    });

    // Search input handling
    searchInput.addEventListener('input', (e) => {
        const query = e.target.value.toLowerCase();
        
        if (query.length < 2) {
            searchResults.innerHTML = `
                <div class="search-hint">
                    <p>Try searching for: <span class="search-tag">MFCC</span> <span class="search-tag">Librosa</span> <span class="search-tag">LSTM</span></p>
                </div>
            `;
            return;
        }

        const results = searchData.filter(item => 
            item.title.toLowerCase().includes(query) || 
            item.description.toLowerCase().includes(query)
        );

        if (results.length === 0) {
            searchResults.innerHTML = `
                <div class="search-hint">
                    <p>No results found for "${query}"</p>
                </div>
            `;
            return;
        }

        searchResults.innerHTML = results.map(item => `
            <div class="search-result-item" data-section="${item.section}">
                <strong>${item.title}</strong>
                <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 0.25rem;">
                    ${item.description}
                </p>
            </div>
        `).join('');

        // Add click handlers to results
        document.querySelectorAll('.search-result-item').forEach(item => {
            item.addEventListener('click', () => {
                const section = item.dataset.section;
                searchModal.classList.remove('active');
                document.querySelector(section)?.scrollIntoView({ behavior: 'smooth' });
            });
        });
    });

    // Keyboard shortcut
    document.addEventListener('keydown', (e) => {
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            searchModal.classList.add('active');
            searchInput.focus();
        }
        if (e.key === 'Escape') {
            searchModal.classList.remove('active');
        }
    });
}

// ============================================================================
// TYPING ANIMATION
// ============================================================================
const typingText = document.getElementById('typingText');
const phrases = [
    'Speech-to-Text Models',
    'Voice Assistants',
    'Audio Deep Learning',
    'Speaker Recognition',
    'Language Models',
    'Transcription Services'
];

if (typingText) {
    let phraseIndex = 0;
    let charIndex = 0;
    let isDeleting = false;
    let typingSpeed = 100;

    function type() {
        const currentPhrase = phrases[phraseIndex];
        
        if (isDeleting) {
            typingText.textContent = currentPhrase.substring(0, charIndex - 1);
            charIndex--;
            typingSpeed = 50;
        } else {
            typingText.textContent = currentPhrase.substring(0, charIndex + 1);
            charIndex++;
            typingSpeed = 100;
        }

        if (!isDeleting && charIndex === currentPhrase.length) {
            isDeleting = true;
            typingSpeed = 2000; // Pause at end
        } else if (isDeleting && charIndex === 0) {
            isDeleting = false;
            phraseIndex = (phraseIndex + 1) % phrases.length;
            typingSpeed = 500; // Pause before next phrase
        }

        setTimeout(type, typingSpeed);
    }

    type();
}

// ============================================================================
// MOBILE MENU
// ============================================================================
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');

if (mobileMenuBtn && mobileMenu) {
    mobileMenuBtn.addEventListener('click', () => {
        mobileMenu.classList.toggle('active');
        mobileMenuBtn.classList.toggle('active');
    });

    const mobileLinks = document.querySelectorAll('.mobile-link');
    mobileLinks.forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.remove('active');
            mobileMenuBtn.classList.remove('active');
        });
    });
}

// ============================================================================
// SMOOTH SCROLLING - FIXED TO PREVENT REFRESH
// ============================================================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        
        const href = this.getAttribute('href');
        if (href && href !== '#') {
            const target = document.querySelector(href);
            if (target) {
                // Close mobile menu if open
                if (mobileMenu && mobileMenu.classList.contains('active')) {
                    mobileMenu.classList.remove('active');
                    mobileMenuBtn.classList.remove('active');
                }
                
                // Smooth scroll to target
                const navHeight = document.querySelector('.navbar')?.offsetHeight || 70;
                const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navHeight;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
                
                // Update URL without page jump
                history.pushState(null, null, href);
            }
        }
        return false;
    });
});

// Prevent form submissions from refreshing page
document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', (e) => {
        e.preventDefault();
    });
});

// Handle download buttons - prevent refresh
document.querySelectorAll('.btn-download, .btn-github').forEach(btn => {
    btn.addEventListener('click', (e) => {
        // Allow download links to work but show toast
        if (btn.classList.contains('btn-download')) {
            showToast('šŸ“¦ Preparing download...');
        }
    });
});

// ============================================================================
// COUNTER ANIMATION
// ============================================================================
const animateCounter = (element, target, duration = 2000) => {
    let start = 0;
    const increment = target / (duration / 16);
    
    const updateCounter = () => {
        start += increment;
        if (start < target) {
            element.textContent = Math.floor(start).toLocaleString();
            requestAnimationFrame(updateCounter);
        } else {
            element.textContent = target.toLocaleString();
        }
    };
    
    updateCounter();
};

const observerOptions = {
    threshold: 0.5,
    rootMargin: '0px'
};

const counterObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const statNumber = entry.target.querySelector('.stat-number');
            if (statNumber && !statNumber.dataset.animated) {
                const target = parseInt(statNumber.dataset.count);
                animateCounter(statNumber, target);
                statNumber.dataset.animated = 'true';
            }
        }
    });
}, observerOptions);

document.querySelectorAll('.stat-item').forEach(item => {
    counterObserver.observe(item);
});

// ============================================================================
// WAVEFORM CANVAS
// ============================================================================
const waveformCanvas = document.getElementById('waveformCanvas');
if (waveformCanvas) {
    const ctx = waveformCanvas.getContext('2d');
    
    function resizeCanvas() {
        waveformCanvas.width = waveformCanvas.offsetWidth * window.devicePixelRatio;
        waveformCanvas.height = 200 * window.devicePixelRatio;
        ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    const drawWaveform = () => {
        const width = waveformCanvas.offsetWidth;
        const height = 200;
        
        ctx.clearRect(0, 0, width, height);
        
        // Draw gradient background
        const gradient = ctx.createLinearGradient(0, 0, width, 0);
        gradient.addColorStop(0, 'rgba(99, 102, 241, 0.3)');
        gradient.addColorStop(0.5, 'rgba(139, 92, 246, 0.3)');
        gradient.addColorStop(1, 'rgba(236, 72, 153, 0.3)');
        
        ctx.strokeStyle = gradient;
        ctx.lineWidth = 3;
        ctx.beginPath();
        
        const centerY = height / 2;
        const time = Date.now() * 0.001;
        
        for (let x = 0; x < width; x++) {
            const y = centerY + 
                Math.sin(x * 0.02 + time) * 30 +
                Math.sin(x * 0.01 + time * 1.5) * 20 +
                Math.sin(x * 0.03 + time * 0.8) * 15;
            
            if (x === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        
        ctx.stroke();
        
        // Draw secondary wave
        ctx.strokeStyle = 'rgba(99, 102, 241, 0.5)';
        ctx.lineWidth = 2;
        ctx.beginPath();
        
        for (let x = 0; x < width; x++) {
            const y = centerY + 
                Math.sin(x * 0.015 + time * 1.2) * 25 +
                Math.cos(x * 0.02 + time) * 15;
            
            if (x === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        
        ctx.stroke();
        
        requestAnimationFrame(drawWaveform);
    };
    
    drawWaveform();
}

// ============================================================================
// SPECTROGRAM VISUALIZATION
// ============================================================================
const spectrogramCanvas = document.getElementById('spectrogramCanvas');
const specBtns = document.querySelectorAll('.spec-btn');
let currentVisualization = 'waveform';

if (spectrogramCanvas) {
    const ctx = spectrogramCanvas.getContext('2d');
    
    function resizeSpectrogramCanvas() {
        spectrogramCanvas.width = spectrogramCanvas.parentElement.offsetWidth * window.devicePixelRatio;
        spectrogramCanvas.height = spectrogramCanvas.parentElement.offsetHeight * window.devicePixelRatio;
        ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    
    resizeSpectrogramCanvas();
    window.addEventListener('resize', resizeSpectrogramCanvas);
    
    // Visualization type buttons
    specBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            specBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentVisualization = btn.dataset.type;
        });
    });
    
    function drawSpectrogram() {
        const width = spectrogramCanvas.parentElement.offsetWidth;
        const height = spectrogramCanvas.parentElement.offsetHeight;
        const time = Date.now() * 0.001;
        
        ctx.clearRect(0, 0, width, height);
        
        if (currentVisualization === 'waveform') {
            // Draw waveform
            ctx.strokeStyle = '#6366f1';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            for (let x = 0; x < width; x++) {
                const y = height / 2 + 
                    Math.sin(x * 0.02 + time) * (height * 0.3) +
                    Math.sin(x * 0.05 + time * 1.5) * (height * 0.1);
                
                if (x === 0) ctx.moveTo(x, y);
                else ctx.lineTo(x, y);
            }
            ctx.stroke();
            
        } else if (currentVisualization === 'spectrogram') {
            // Draw spectrogram bars
            const barWidth = 4;
            const barGap = 2;
            const numBars = Math.floor(width / (barWidth + barGap));
            
            for (let i = 0; i < numBars; i++) {
                const barHeight = Math.abs(Math.sin(i * 0.1 + time) * 
                    Math.sin(i * 0.05 + time * 1.5)) * height * 0.8 + height * 0.1;
                
                const hue = 250 + (i / numBars) * 60;
                ctx.fillStyle = `hsla(${hue}, 70%, 60%, 0.8)`;
                
                const x = i * (barWidth + barGap);
                const y = (height - barHeight) / 2;
                ctx.fillRect(x, y, barWidth, barHeight);
            }
            
        } else if (currentVisualization === 'frequency') {
            // Draw frequency circles
            const numCircles = 8;
            
            for (let i = 0; i < numCircles; i++) {
                const radius = (i + 1) * (Math.min(width, height) / (numCircles * 2.5));
                const amplitude = Math.sin(time + i * 0.5) * 10;
                
                ctx.strokeStyle = `hsla(${250 + i * 15}, 70%, 60%, ${0.3 + (numCircles - i) * 0.05})`;
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(width / 2, height / 2, radius + amplitude, 0, Math.PI * 2);
                ctx.stroke();
            }
        }
        
        requestAnimationFrame(drawSpectrogram);
    }
    
    drawSpectrogram();
}

// ============================================================================
// WEB AUDIO API - AUDIO CONTEXT
// ============================================================================
let audioContext = null;
let currentOscillator = null;
let currentGainNode = null;

function initAudioContext() {
    if (!audioContext) {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
    }
    if (audioContext.state === 'suspended') {
        audioContext.resume();
    }
    return audioContext;
}

// Generate speech-like sound using oscillators
function playSpeechSound(duration = 2, transcript = '') {
    const ctx = initAudioContext();
    
    // Stop any currently playing sound
    stopCurrentSound();
    
    const masterGain = ctx.createGain();
    masterGain.connect(ctx.destination);
    masterGain.gain.setValueAtTime(0.3, ctx.currentTime);
    
    currentGainNode = masterGain;
    
    // Create multiple oscillators for richer sound
    const oscillators = [];
    const frequencies = [150, 300, 450, 600]; // Formant-like frequencies
    
    frequencies.forEach((freq, index) => {
        const osc = ctx.createOscillator();
        const oscGain = ctx.createGain();
        
        osc.type = index === 0 ? 'sawtooth' : 'sine';
        osc.frequency.setValueAtTime(freq, ctx.currentTime);
        
        // Add slight vibrato
        const vibrato = ctx.createOscillator();
        const vibratoGain = ctx.createGain();
        vibrato.frequency.setValueAtTime(5, ctx.currentTime);
        vibratoGain.gain.setValueAtTime(freq * 0.02, ctx.currentTime);
        vibrato.connect(vibratoGain);
        vibratoGain.connect(osc.frequency);
        vibrato.start();
        
        // Simulate speech patterns with frequency changes
        const speechPattern = generateSpeechPattern(duration, transcript);
        speechPattern.forEach((change, i) => {
            osc.frequency.setValueAtTime(
                freq * change.multiplier,
                ctx.currentTime + change.time
            );
        });
        
        oscGain.gain.setValueAtTime(0.15 / (index + 1), ctx.currentTime);
        
        osc.connect(oscGain);
        oscGain.connect(masterGain);
        
        osc.start();
        oscillators.push({ osc, vibrato, oscGain });
    });
    
    // Envelope for natural speech
    masterGain.gain.setValueAtTime(0, ctx.currentTime);
    masterGain.gain.linearRampToValueAtTime(0.3, ctx.currentTime + 0.05);
    masterGain.gain.setValueAtTime(0.3, ctx.currentTime + duration - 0.1);
    masterGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration);
    
    // Stop oscillators after duration
    setTimeout(() => {
        oscillators.forEach(({ osc, vibrato }) => {
            osc.stop();
            vibrato.stop();
        });
    }, duration * 1000);
    
    currentOscillator = oscillators;
    
    return duration;
}

function generateSpeechPattern(duration, transcript) {
    const pattern = [];
    const words = transcript.split(' ').length || 3;
    const wordDuration = duration / words;
    
    for (let i = 0; i < words; i++) {
        const wordStart = i * wordDuration;
        // Pitch variation for each word
        pattern.push({ time: wordStart, multiplier: 0.9 + Math.random() * 0.3 });
        pattern.push({ time: wordStart + wordDuration * 0.3, multiplier: 1 + Math.random() * 0.2 });
        pattern.push({ time: wordStart + wordDuration * 0.7, multiplier: 0.95 + Math.random() * 0.1 });
    }
    return pattern;
}

function stopCurrentSound() {
    if (currentOscillator) {
        try {
            if (Array.isArray(currentOscillator)) {
                currentOscillator.forEach(({ osc, vibrato }) => {
                    osc.stop();
                    vibrato.stop();
                });
            }
        } catch (e) {}
        currentOscillator = null;
    }
    if (currentGainNode) {
        currentGainNode.gain.setValueAtTime(0, audioContext?.currentTime || 0);
    }
}

// Play a simple beep sound for UI feedback
function playBeep(frequency = 440, duration = 0.1) {
    const ctx = initAudioContext();
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    
    osc.type = 'sine';
    osc.frequency.setValueAtTime(frequency, ctx.currentTime);
    gain.gain.setValueAtTime(0.1, ctx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + duration);
    
    osc.connect(gain);
    gain.connect(ctx.destination);
    
    osc.start();
    osc.stop(ctx.currentTime + duration);
}

// ============================================================================
// MAIN AUDIO PLAYER - Uses Browser Speech Synthesis
// ============================================================================
const playBtn = document.getElementById('playBtn');
const progressBar = document.getElementById('progressBar');
const timeDisplay = document.getElementById('timeDisplay');
const volumeSlider = document.getElementById('volumeSlider');
const volumeIcon = document.getElementById('volumeIcon');

// Main player transcript
const mainTranscript = "Hello, how are you today?";
let mainIsPlaying = false;

// Volume controls
function updateVolumeIcon(volume) {
    if (volumeIcon) {
        if (volume === 0) {
            volumeIcon.className = 'fas fa-volume-mute';
        } else if (volume < 50) {
            volumeIcon.className = 'fas fa-volume-down';
        } else {
            volumeIcon.className = 'fas fa-volume-up';
        }
    }
}

if (volumeSlider) {
    volumeSlider.addEventListener('input', (e) => {
        const volume = parseInt(e.target.value);
        updateVolumeIcon(volume);
    });
}

if (volumeIcon && volumeSlider) {
    let previousVolume = 70;
    volumeIcon.addEventListener('click', () => {
        if (parseInt(volumeSlider.value) > 0) {
            previousVolume = volumeSlider.value;
            volumeSlider.value = 0;
        } else {
            volumeSlider.value = previousVolume;
        }
        updateVolumeIcon(parseInt(volumeSlider.value));
    });
}

// Main play button
if (playBtn) {
    playBtn.addEventListener('click', () => {
        if (!mainIsPlaying) {
            // Start speaking
            mainIsPlaying = true;
            playBtn.innerHTML = '<i class="fas fa-pause"></i>';
            
            showToast(`šŸ”Š Speaking: "${mainTranscript}"`);
            
            // Animate progress bar
            progressBar.style.transition = 'width 2s linear';
            progressBar.style.width = '100%';
            timeDisplay.textContent = '0:00 / 0:02';
            
            // Speak the text
            speakText(mainTranscript, () => {
                // Reset when done
                mainIsPlaying = false;
                playBtn.innerHTML = '<i class="fas fa-play"></i>';
                progressBar.style.transition = 'none';
                progressBar.style.width = '0%';
                timeDisplay.textContent = '0:00 / 0:02';
            });
            
            // Update time display
            let elapsed = 0;
            const timeInterval = setInterval(() => {
                elapsed++;
                if (elapsed <= 2 && mainIsPlaying) {
                    timeDisplay.textContent = `0:0${elapsed} / 0:02`;
                } else {
                    clearInterval(timeInterval);
                }
            }, 1000);
            
        } else {
            // Stop speaking
            mainIsPlaying = false;
            playBtn.innerHTML = '<i class="fas fa-play"></i>';
            stopSpeaking();
            progressBar.style.transition = 'none';
            progressBar.style.width = '0%';
            timeDisplay.textContent = '0:00 / 0:02';
        }
    });
}

// ============================================================================
// SAMPLE WAVEFORMS
// ============================================================================
document.querySelectorAll('.sample-waveform').forEach((waveform, index) => {
    const canvas = document.createElement('canvas');
    canvas.width = waveform.offsetWidth || 300;
    canvas.height = waveform.offsetHeight || 100;
    waveform.appendChild(canvas);
    
    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;
    
    // Generate random but consistent waveform data
    const waveData = [];
    for (let i = 0; i < width / 3; i++) {
        waveData.push(Math.random() * 0.6 + 0.2);
    }
    
    const drawSampleWaveform = () => {
        ctx.clearRect(0, 0, width, height);
        
        const barWidth = 2;
        const barSpacing = 1;
        const time = Date.now() * 0.001;
        
        waveData.forEach((value, i) => {
            const animatedValue = value * (0.8 + Math.sin(time + i * 0.2) * 0.2);
            const barHeight = animatedValue * height;
            const x = i * (barWidth + barSpacing);
            const y = (height - barHeight) / 2;
            
            const gradient = ctx.createLinearGradient(x, y, x, y + barHeight);
            gradient.addColorStop(0, 'rgba(99, 102, 241, 0.8)');
            gradient.addColorStop(1, 'rgba(139, 92, 246, 0.8)');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(x, y, barWidth, barHeight);
        });
        
        requestAnimationFrame(drawSampleWaveform);
    };
    
    drawSampleWaveform();
});

// ============================================================================
// CHARTS
// ============================================================================
const speakerChart = document.getElementById('speakerChart');
const durationChart = document.getElementById('durationChart');
const wordChart = document.getElementById('wordChart');

if (speakerChart && typeof Chart !== 'undefined') {
    new Chart(speakerChart, {
        type: 'doughnut',
        data: {
            labels: ['Male', 'Female', 'Other'],
            datasets: [{
                data: [30, 18, 2],
                backgroundColor: [
                    'rgba(99, 102, 241, 0.8)',
                    'rgba(139, 92, 246, 0.8)',
                    'rgba(236, 72, 153, 0.8)'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#cbd5e1',
                        padding: 20
                    }
                }
            },
            cutout: '60%'
        }
    });
}

if (durationChart && typeof Chart !== 'undefined') {
    new Chart(durationChart, {
        type: 'bar',
        data: {
            labels: ['0-1s', '1-2s', '2-3s', '3-4s', '4-5s', '5s+'],
            datasets: [{
                label: 'Number of Samples',
                data: [500, 1200, 1800, 1000, 400, 100],
                backgroundColor: 'rgba(99, 102, 241, 0.8)',
                borderRadius: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { color: '#cbd5e1' },
                    grid: { color: 'rgba(51, 65, 85, 0.3)' }
                },
                x: {
                    ticks: { color: '#cbd5e1' },
                    grid: { color: 'rgba(51, 65, 85, 0.3)' }
                }
            }
        }
    });
}

if (wordChart && typeof Chart !== 'undefined') {
    new Chart(wordChart, {
        type: 'line',
        data: {
            labels: ['the', 'hello', 'please', 'what', 'how', 'turn', 'set', 'weather'],
            datasets: [{
                label: 'Frequency',
                data: [1200, 800, 600, 500, 450, 400, 350, 300],
                borderColor: 'rgba(99, 102, 241, 1)',
                backgroundColor: 'rgba(99, 102, 241, 0.1)',
                tension: 0.4,
                fill: true,
                pointBackgroundColor: 'rgba(99, 102, 241, 1)',
                pointBorderColor: '#fff',
                pointBorderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { color: '#cbd5e1' },
                    grid: { color: 'rgba(51, 65, 85, 0.3)' }
                },
                x: {
                    ticks: { color: '#cbd5e1' },
                    grid: { color: 'rgba(51, 65, 85, 0.3)' }
                }
            }
        }
    });
}

// ============================================================================
// CODE TABS
// ============================================================================
const tabBtns = document.querySelectorAll('.tab-btn');
const codeBlocks = document.querySelectorAll('.code-block');

tabBtns.forEach(btn => {
    if (btn.dataset.tab) {
        btn.addEventListener('click', () => {
            tabBtns.forEach(b => {
                if (b.dataset.tab) b.classList.remove('active');
            });
            codeBlocks.forEach(block => block.classList.remove('active'));
            
            btn.classList.add('active');
            document.getElementById(btn.dataset.tab)?.classList.add('active');
        });
    }
});

// ============================================================================
// COPY CODE BUTTON
// ============================================================================
const copyCodeBtn = document.getElementById('copyCodeBtn');

if (copyCodeBtn) {
    copyCodeBtn.addEventListener('click', () => {
        const activeCodeBlock = document.querySelector('.code-block.active code');
        if (activeCodeBlock) {
            const code = activeCodeBlock.textContent;
            navigator.clipboard.writeText(code).then(() => {
                copyCodeBtn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                copyCodeBtn.classList.add('copied');
                showToast('Code copied to clipboard!');
                
                setTimeout(() => {
                    copyCodeBtn.innerHTML = '<i class="fas fa-copy"></i> Copy Code';
                    copyCodeBtn.classList.remove('copied');
                }, 2000);
            });
        }
    });
}

// Copy code buttons in "How to Use" section
document.querySelectorAll('.code-example .copy-code-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const codeId = btn.getAttribute('data-code');
        const codeElement = document.getElementById(codeId);
        
        if (codeElement) {
            const code = codeElement.textContent;
            navigator.clipboard.writeText(code).then(() => {
                const icon = btn.querySelector('i');
                const originalClass = icon ? icon.className : 'fas fa-copy';
                
                btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                btn.classList.add('copied');
                showToast('Code copied to clipboard!', 'success');
                
                setTimeout(() => {
                    btn.innerHTML = `<i class="${originalClass}"></i> Copy`;
                    btn.classList.remove('copied');
                }, 2000);
            }).catch(() => {
                showToast('Failed to copy code', 'error');
            });
        }
    });
});

// ============================================================================
// FAQ ACCORDION
// ============================================================================
document.querySelectorAll('.faq-question').forEach(question => {
    question.addEventListener('click', () => {
        const faqItem = question.parentElement;
        const isActive = faqItem.classList.contains('active');
        
        // Close all FAQ items
        document.querySelectorAll('.faq-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // Open clicked item if it wasn't active
        if (!isActive) {
            faqItem.classList.add('active');
        }
    });
});

// ============================================================================
// BROWSER SPEECH SYNTHESIS - Speaks actual words!
// ============================================================================
const speechSynthesis = window.speechSynthesis;
let currentUtterance = null;

// Sample data with transcripts
const sampleData = [
    { transcript: "Hello, how are you today?" },
    { transcript: "Please turn on the lights" },
    { transcript: "What's the weather like outside?" },
    { transcript: "Set a timer for five minutes" }
];

// Load voices (needed for some browsers)
let voicesLoaded = false;
speechSynthesis.onvoiceschanged = () => {
    voicesLoaded = true;
};

// Function to speak text using browser TTS
function speakText(text, onEnd) {
    // Cancel any current speech
    speechSynthesis.cancel();
    
    // Create utterance
    currentUtterance = new SpeechSynthesisUtterance(text);
    currentUtterance.rate = 1.0;  // Speed
    currentUtterance.pitch = 1.0; // Pitch
    currentUtterance.volume = 1.0; // Volume
    
    // Try to get a good English voice
    const voices = speechSynthesis.getVoices();
    if (voices.length > 0) {
        const englishVoice = voices.find(v => v.lang.startsWith('en')) || voices[0];
        if (englishVoice) {
            currentUtterance.voice = englishVoice;
        }
    }
    
    currentUtterance.onend = onEnd;
    currentUtterance.onerror = onEnd;
    
    speechSynthesis.speak(currentUtterance);
}

// Stop speaking
function stopSpeaking() {
    speechSynthesis.cancel();
    currentUtterance = null;
}

// Sample play buttons
document.querySelectorAll('.sample-play-btn').forEach((btn, index) => {
    btn.addEventListener('click', (e) => {
        e.preventDefault();
        const icon = btn.querySelector('i');
        const sample = sampleData[index] || sampleData[0];
        
        if (icon.classList.contains('fa-play')) {
            // Stop all other samples
            document.querySelectorAll('.sample-play-btn').forEach((otherBtn) => {
                const otherIcon = otherBtn.querySelector('i');
                if (otherIcon.classList.contains('fa-pause')) {
                    otherIcon.classList.remove('fa-pause');
                    otherIcon.classList.add('fa-play');
                }
            });
            stopSpeaking();
            stopCurrentSound();
            
            // Play this sample
            icon.classList.remove('fa-play');
            icon.classList.add('fa-pause');
            
            // Speak the actual text!
            showToast(`šŸ”Š Speaking: "${sample.transcript}"`);
            speakText(sample.transcript, () => {
                icon.classList.remove('fa-pause');
                icon.classList.add('fa-play');
            });
            
        } else {
            // Stop
            icon.classList.remove('fa-pause');
            icon.classList.add('fa-play');
            stopSpeaking();
        }
    });
});

// ============================================================================
// NEWSLETTER FORM
// ============================================================================
const newsletterForm = document.getElementById('newsletterForm');

if (newsletterForm) {
    newsletterForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const email = newsletterForm.querySelector('input[type="email"]').value;
        
        // Simulate subscription
        showToast('Thank you for subscribing!');
        newsletterForm.reset();
    });
}

// ============================================================================
// TOAST NOTIFICATION
// ============================================================================
function showToast(message) {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toastMessage');
    
    if (toast && toastMessage) {
        toastMessage.textContent = message;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// ============================================================================
// BACK TO TOP BUTTON
// ============================================================================
const backToTop = document.getElementById('backToTop');

if (backToTop) {
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTop.classList.add('visible');
        } else {
            backToTop.classList.remove('visible');
        }
    });
    
    backToTop.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// ============================================================================
// FLOATING PARTICLES
// ============================================================================
const particlesContainer = document.getElementById('particles');
if (particlesContainer) {
    for (let i = 0; i < 30; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        particle.style.cssText = `
            position: absolute;
            width: ${Math.random() * 6 + 2}px;
            height: ${particle.style.width};
            background: rgba(99, 102, 241, ${Math.random() * 0.3 + 0.1});
            border-radius: 50%;
            left: ${Math.random() * 100}%;
            top: ${Math.random() * 100}%;
            animation: float ${Math.random() * 15 + 10}s infinite ease-in-out;
            animation-delay: ${Math.random() * 5}s;
        `;
        particlesContainer.appendChild(particle);
    }
}

// Add floating animation
const floatStyle = document.createElement('style');
floatStyle.textContent = `
    @keyframes float {
        0%, 100% {
            transform: translate(0, 0) rotate(0deg);
            opacity: 0.3;
        }
        25% {
            transform: translate(${Math.random() * 50 - 25}px, ${Math.random() * 50 - 25}px) rotate(90deg);
        }
        50% {
            transform: translate(${Math.random() * 50 - 25}px, ${Math.random() * 50 - 25}px) rotate(180deg);
            opacity: 0.6;
        }
        75% {
            transform: translate(${Math.random() * 50 - 25}px, ${Math.random() * 50 - 25}px) rotate(270deg);
        }
    }
`;
document.head.appendChild(floatStyle);

// ============================================================================
// SCROLL REVEAL ANIMATION
// ============================================================================
const revealElements = document.querySelectorAll('.feature-card, .sample-card, .use-case-card, .stats-card');

const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, { threshold: 0.1 });

revealElements.forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(30px)';
    el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    revealObserver.observe(el);
});

// ============================================================================
// NAVBAR SCROLL EFFECT
// ============================================================================
const navbar = document.querySelector('.navbar');

window.addEventListener('scroll', () => {
    if (window.pageYOffset > 50) {
        navbar.style.background = 'rgba(15, 23, 42, 0.95)';
        navbar.style.boxShadow = '0 4px 30px rgba(0, 0, 0, 0.3)';
    } else {
        navbar.style.background = 'rgba(15, 23, 42, 0.8)';
        navbar.style.boxShadow = 'none';
    }
});

// ============================================================================
// CONSOLE EASTER EGG
// ============================================================================
console.log('%cšŸŽ™ļø Speech Recognition Dataset', 'font-size: 24px; font-weight: bold; color: #6366f1;');
console.log('%cDeveloped by Molla Samser - RSK World', 'font-size: 14px; color: #8b5cf6;');
console.log('%cWebsite: https://rskworld.in', 'font-size: 12px; color: #cbd5e1;');
console.log('%c© 2026 RSK World. All rights reserved.', 'font-size: 11px; color: #94a3b8;');
1,239 lines•44 KB
javascript

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer