Code ExampleReactVanilla
Quick Start
Create your first voice-enabled application in under 5 minutes.
Basic Setup
Here is a complete "Hello World" example. This snippet initializes JSVoice, adds a simple command, and allows you to toggle the microphone.
html
1<!DOCTYPE html>
2<html>
3<head>
4 <title>JSVoice Demo</title>
5</head>
6<body>
7 <button id="micBtn">🎤 Start Listening</button>
8 <p id="status">Click the button to start</p>
9
10 <script type="module">
11 import JSVoice from './node_modules/jsvoice/dist/voice-ui.esm.js';
12
13 // 1. Initialize
14 const voice = new JSVoice({
15 onStatusChange: (msg) => {
16 document.getElementById('status').textContent = msg;
17 }
18 });
19
20 // 2. Add Command
21 voice.addCommand('hello world', () => {
22 alert('Hello, World!');
23 voice.speak('Hello to you too!');
24 });
25
26 // 3. Toggle Listen
27 document.getElementById('micBtn').addEventListener('click', () => {
28 voice.toggle();
29 });
30 </script>
31</body>
32</html>React Example
Using JSVoice in a React component is just as simple.
jsx
1import { useEffect, useState } from 'react';
2import JSVoice from 'jsvoice';
3
4export default function VoiceComponent() {
5 const [status, setStatus] = useState('Idle');
6 const [voice] = useState(() => new JSVoice({
7 onStatusChange: setStatus
8 }));
9
10 useEffect(() => {
11 // Add commands on mount
12 voice.addCommand('scroll down', () => window.scrollBy(0, 500));
13
14 // Cleanup on unmount
15 return () => voice.stop();
16 }, [voice]);
17
18 return (
19 <div>
20 <p>Status: {status}</p>
21 <button onClick={() => voice.toggle()}>
22 Toggle Voice
23 </button>
24 </div>
25 );
26}