File size: 9,799 Bytes
5454980
fe87343
5454980
fe87343
 
612f193
5454980
 
612f193
5454980
621a9fb
5454980
612f193
5454980
fe87343
612f193
fe87343
612f193
fe87343
 
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe87343
 
612f193
 
621a9fb
612f193
5454980
612f193
 
5454980
612f193
 
 
 
 
 
 
 
 
 
fe87343
612f193
 
 
 
 
 
621a9fb
612f193
 
 
5454980
fe87343
612f193
 
fe87343
612f193
 
fe87343
 
5454980
 
 
fe87343
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe87343
621a9fb
5454980
 
612f193
 
 
 
 
 
5454980
612f193
 
 
 
 
 
 
 
 
5454980
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe87343
612f193
 
 
 
 
 
 
 
 
 
5454980
612f193
 
 
 
 
 
 
5454980
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621a9fb
fe87343
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621a9fb
612f193
621a9fb
612f193
 
 
 
 
 
 
 
 
 
fe87343
612f193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe87343
612f193
 
fe87343
5454980
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Voice Assistant Demo</title>
    <style>
        body {
            font-family: system-ui, -apple-system, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f0f0f0;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .status {
            margin: 20px 0;
            padding: 10px;
            border-radius: 4px;
            background: #e8f5e9;
        }
        .transcript {
            margin: 20px 0;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 4px;
            min-height: 50px;
        }
        button {
            background: #2196F3;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background: #1976D2;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }
        .voice-settings {
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        .setting-group {
            margin: 10px 0;
        }
        label {
            display: inline-block;
            width: 100px;
        }
        .error {
            background: #ffebee;
            color: #c62828;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Voice Assistant Demo</h1>
        <p>Click "Start Listening" and speak a command. Try saying:</p>
        <ul>
            <li>"Hello" - The assistant will greet you back</li>
            <li>"What time is it?" - Get the current time</li>
            <li>"Tell me a fact" - Hear an interesting fact</li>
        </ul>

        <div class="controls">
            <button id="startBtn">Start Listening</button>
            <button id="stopBtn" disabled>Stop Listening</button>
        </div>

        <div class="error" id="error"></div>
        <div class="status" id="status">Status: Ready</div>
        <div class="transcript" id="transcript"></div>

        <div class="voice-settings">
            <h3>Voice Settings</h3>
            <div class="setting-group">
                <label for="voice">Voice:</label>
                <select id="voice"></select>
            </div>
            <div class="setting-group">
                <label for="rate">Rate:</label>
                <input type="range" id="rate" min="0.5" max="2" value="1" step="0.1">
                <span id="rateValue">1</span>
            </div>
            <div class="setting-group">
                <label for="pitch">Pitch:</label>
                <input type="range" id="pitch" min="0.5" max="2" value="1" step="0.1">
                <span id="pitchValue">1</span>
            </div>
        </div>
    </div>

    <script>
        // Check if speech recognition is supported
        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            document.getElementById('error').style.display = 'block';
            document.getElementById('error').textContent = 'Speech recognition is not supported in this browser. Please try Chrome.';
            document.getElementById('startBtn').disabled = true;
        }

        // Initialize speech recognition
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const recognition = new SpeechRecognition();
        
        // Configure recognition
        recognition.continuous = false;
        recognition.lang = 'en-US';
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        // Initialize speech synthesis
        const synth = window.speechSynthesis;
        let voices = [];

        // DOM elements
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const status = document.getElementById('status');
        const transcript = document.getElementById('transcript');
        const voiceSelect = document.getElementById('voice');
        const rate = document.getElementById('rate');
        const pitch = document.getElementById('pitch');
        const rateValue = document.getElementById('rateValue');
        const pitchValue = document.getElementById('pitchValue');
        const errorDiv = document.getElementById('error');

        // Populate voice list
        function populateVoices() {
            voices = synth.getVoices();
            voiceSelect.innerHTML = '';
            voices.forEach((voice, i) => {
                const option = document.createElement('option');
                option.textContent = `${voice.name} (${voice.lang})`;
                option.setAttribute('data-name', voice.name);
                voiceSelect.appendChild(option);
            });
        }

        populateVoices();
        if (speechSynthesis.onvoiceschanged !== undefined) {
            speechSynthesis.onvoiceschanged = populateVoices;
        }

        // Speech synthesis function
        function speak(text) {
            if (synth.speaking) {
                console.error('speechSynthesis.speaking');
                return;
            }
            const utterance = new SpeechSynthesisUtterance(text);
            const selectedVoice = voices[voiceSelect.selectedIndex];
            utterance.voice = selectedVoice;
            utterance.rate = rate.value;
            utterance.pitch = pitch.value;
            synth.speak(utterance);
        }

        // Handle commands
        function handleCommand(command) {
            command = command.toLowerCase();
            let response = '';

            if (command.includes('hello')) {
                response = 'Hello! How can I help you today?';
            } else if (command.includes('what time')) {
                const now = new Date();
                response = `The current time is ${now.toLocaleTimeString()}`;
            } else if (command.includes('tell me a fact')) {
                const facts = [
                    'The shortest war in history was between Britain and Zanzibar on August 27, 1896. Zanzibar surrendered after just 38 minutes.',
                    'Honey never spoils. Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old and still perfectly good to eat.',
                    'The first oranges weren't orange. The original oranges from Southeast Asia were actually green.',
                ];
                response = facts[Math.floor(Math.random() * facts.length)];
            } else {
                response = "I'm sorry, I didn't understand that command. Please try again.";
            }

            transcript.textContent = `You said: ${command}\nAssistant: ${response}`;
            speak(response);
        }

        // Event listeners
        startBtn.addEventListener('click', () => {
            errorDiv.style.display = 'none';
            try {
                recognition.start();
                startBtn.disabled = true;
                stopBtn.disabled = false;
                status.textContent = 'Status: Listening...';
                console.log('Recognition started');
            } catch (err) {
                console.error('Recognition error:', err);
                errorDiv.style.display = 'block';
                errorDiv.textContent = `Error starting recognition: ${err.message}`;
            }
        });

        stopBtn.addEventListener('click', () => {
            try {
                recognition.stop();
                startBtn.disabled = false;
                stopBtn.disabled = true;
                status.textContent = 'Status: Stopped';
            } catch (err) {
                console.error('Stop error:', err);
                errorDiv.style.display = 'block';
                errorDiv.textContent = `Error stopping recognition: ${err.message}`;
            }
        });

        recognition.onstart = () => {
            console.log('Recognition started');
            status.textContent = 'Status: Listening...';
        };

        recognition.onresult = (event) => {
            console.log('Recognition result received');
            const command = event.results[0][0].transcript;
            handleCommand(command);
        };

        recognition.onend = () => {
            console.log('Recognition ended');
            startBtn.disabled = false;
            stopBtn.disabled = true;
            status.textContent = 'Status: Ready';
        };

        recognition.onerror = (event) => {
            console.error('Recognition error:', event.error);
            errorDiv.style.display = 'block';
            errorDiv.textContent = `Error: ${event.error}. ${event.error === 'not-allowed' ? 'Please ensure microphone permissions are granted.' : ''}`;
            status.textContent = 'Status: Error';
            startBtn.disabled = false;
            stopBtn.disabled = true;
        };

        // Voice setting controls
        rate.addEventListener('input', () => {
            rateValue.textContent = rate.value;
        });

        pitch.addEventListener('input', () => {
            pitchValue.textContent = pitch.value;
        });
    </script>
</body>
</html>