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
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
fitness-coach-bot
/
utils
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
utils
  • __pycache__
  • __init__.py965 B
  • ai_workout_generator.py18 KB
  • analytics_engine.py27.8 KB
  • fitness_coach.py13.3 KB
  • gamification_system.py30.4 KB
  • nutrition_ai.py23.8 KB
  • smart_recovery.py11 KB
  • social_features.py19.4 KB
  • voice_coach.py10 KB
  • wearable_integration.py27 KB
  • workout_buddy_matcher.py9.5 KB
voice_recognition.js
static/js/voice_recognition.js
Raw Download
Find: Go to:
/**
 * Voice Recognition for Hands-Free Workouts
 * Author: RSK World (https://rskworld.in)
 * Founded by: Molla Samser
 * Designer & Tester: Rima Khatun
 * Contact: help@rskworld.in, +91 93305 39277
 * Year: 2026
 */

class VoiceRecognition {
    constructor() {
        this.recognition = null;
        this.isListening = false;
        this.onResultCallback = null;
        this.init();
    }

    init() {
        // Check for browser support
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        
        if (!SpeechRecognition) {
            console.warn('Speech recognition not supported in this browser');
            this.showUnsupportedMessage();
            return;
        }

        this.recognition = new SpeechRecognition();
        this.recognition.continuous = false;
        this.recognition.interimResults = false;
        this.recognition.lang = 'en-US';

        this.recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            if (this.onResultCallback) {
                this.onResultCallback(transcript);
            }
        };

        this.recognition.onerror = (event) => {
            console.error('Speech recognition error:', event.error);
            this.handleError(event.error);
        };

        this.recognition.onend = () => {
            this.isListening = false;
            this.updateUI();
        };
    }

    startListening(callback) {
        if (!this.recognition) {
            alert('Voice recognition not supported in your browser');
            return;
        }

        if (this.isListening) {
            this.stopListening();
            return;
        }

        this.onResultCallback = callback;
        this.isListening = true;
        
        try {
            this.recognition.start();
            this.updateUI();
            this.showListeningIndicator();
        } catch (error) {
            console.error('Error starting recognition:', error);
        }
    }

    stopListening() {
        if (this.recognition && this.isListening) {
            this.recognition.stop();
            this.isListening = false;
            this.updateUI();
            this.hideListeningIndicator();
        }
    }

    updateUI() {
        const button = document.getElementById('voiceToggleButton');
        if (button) {
            if (this.isListening) {
                button.innerHTML = '<i class="fas fa-microphone-slash"></i> Stop Listening';
                button.classList.add('btn-danger');
                button.classList.remove('btn-primary');
            } else {
                button.innerHTML = '<i class="fas fa-microphone"></i> Voice Command';
                button.classList.add('btn-primary');
                button.classList.remove('btn-danger');
            }
        }
    }

    showListeningIndicator() {
        let indicator = document.getElementById('voiceListeningIndicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.id = 'voiceListeningIndicator';
            indicator.className = 'voice-listening-indicator';
            indicator.innerHTML = `
                <div class="listening-pulse"></div>
                <p>Listening...</p>
            `;
            document.body.appendChild(indicator);
        }
        indicator.style.display = 'block';
    }

    hideListeningIndicator() {
        const indicator = document.getElementById('voiceListeningIndicator');
        if (indicator) {
            indicator.style.display = 'none';
        }
    }

    handleError(error) {
        let message = 'Voice recognition error occurred';
        
        switch (error) {
            case 'no-speech':
                message = 'No speech detected. Please try again.';
                break;
            case 'audio-capture':
                message = 'No microphone found. Please connect a microphone.';
                break;
            case 'not-allowed':
                message = 'Microphone permission denied. Please allow microphone access.';
                break;
            case 'network':
                message = 'Network error. Please check your connection.';
                break;
        }

        this.showError(message);
        this.stopListening();
    }

    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-warning alert-dismissible fade show position-fixed';
        errorDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        errorDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(errorDiv);

        setTimeout(() => {
            errorDiv.remove();
        }, 5000);
    }

    showUnsupportedMessage() {
        const message = document.createElement('div');
        message.className = 'alert alert-info';
        message.innerHTML = `
            <strong>Voice recognition not available</strong><br>
            Your browser doesn't support voice recognition. Please use Chrome, Edge, or Safari.
        `;
        const voiceSection = document.getElementById('voiceSection');
        if (voiceSection) {
            voiceSection.appendChild(message);
        }
    }

    speak(text) {
        if ('speechSynthesis' in window) {
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = 'en-US';
            utterance.rate = 1.0;
            utterance.pitch = 1.0;
            
            // Use a more natural voice if available
            const voices = speechSynthesis.getVoices();
            const preferredVoice = voices.find(voice => 
                voice.lang.includes('en') && voice.name.includes('Natural')
            ) || voices.find(voice => voice.lang.includes('en-US'));
            
            if (preferredVoice) {
                utterance.voice = preferredVoice;
            }
            
            speechSynthesis.speak(utterance);
        }
    }
}

// Initialize voice recognition
document.addEventListener('DOMContentLoaded', () => {
    window.voiceRecognition = new VoiceRecognition();

    // Setup voice toggle button
    const voiceButton = document.getElementById('voiceToggleButton');
    if (voiceButton) {
        voiceButton.addEventListener('click', () => {
            if (window.voiceRecognition.isListening) {
                window.voiceRecognition.stopListening();
            } else {
                window.voiceRecognition.startListening(async (transcript) => {
                    console.log('Voice command:', transcript);
                    
                    // Send to backend
                    try {
                        const response = await fetch('/api/voice/command', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ transcript: transcript })
                        });
                        
                        const data = await response.json();
                        
                        if (data.success && data.response) {
                            // Display response
                            if (window.fitnessBot) {
                                window.fitnessBot.addMessage(data.response, 'bot');
                            }
                            
                            // Speak response
                            window.voiceRecognition.speak(data.response);
                        }
                    } catch (error) {
                        console.error('Error processing voice command:', error);
                    }
                });
            }
        });
    }
});
235 lines•8 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