npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

jsvoice

v0.2.2

Published

Modern JavaScript voice command library with speech recognition, synthesis, pattern matching, wake word detection, and real-time audio visualization. Zero dependencies, TypeScript ready, perfect for accessibility and voice-first UIs.

Readme

JSVoice

Modern JavaScript Voice Command Library

Add voice control to your web application. Zero dependencies. TypeScript ready.

npm version License: MIT Downloads Bundle Size

DocumentationQuick StartExamplesAPIContributing


What is JSVoice?

JSVoice is a production-ready JavaScript library for adding voice commands and speech synthesis to web applications. Built on the Web Speech API, it provides an intuitive interface for creating voice-enabled experiences with zero dependencies.

Perfect for:

  • Accessibility - Enable hands-free navigation for all users
  • Voice-First Interfaces - Build modern conversational UIs
  • Productivity Tools - Create voice-controlled applications
  • Smart Home Dashboards - Control IoT devices with voice
  • Gaming - Add voice command integration to games

Why Choose JSVoice?

Zero Dependencies

Pure JavaScript with no external libraries. Minimal bundle size at just 32KB minified and gzipped.

TypeScript Support

Full type definitions included for complete IDE autocomplete and type checking.

Production Ready

Comprehensive error handling, extensive documentation, and active maintenance.

Easy to Use

Simple API with clear documentation and working examples to get started in minutes.

Feature Rich

Built-in commands, pattern matching, wake word detection, and real-time audio visualization.


Installation

Using NPM:

npm install jsvoice

Using Yarn:

yarn add jsvoice

Using CDN:

<script src="https://unpkg.com/jsvoice/dist/voice-ui.umd.min.js"></script>

Quick Start

Basic Example

import JSVoice from 'jsvoice';

// Create instance
const voice = new JSVoice({
  onStatusChange: (message) => {
    console.log('Status:', message);
  }
});

// Add a command
voice.addCommand('hello world', () => {
  voice.speak('Hello! How can I help you?');
});

// Start listening
document.getElementById('mic-button').addEventListener('click', () => {
  voice.toggle();
});

That's it! You now have voice commands in your application.


Key Features

Voice Recognition

Real-time speech-to-text conversion with continuous listening mode, automatic restart on failure, and support for 50+ languages including English, Spanish, French, German, Japanese, Chinese, and more.

Speech Synthesis

Text-to-speech output with multiple voices, customizable speech parameters including rate, pitch, and volume, plus intelligent queue management for sequential speech.

Custom Commands

Easy registration of exact phrase commands and pattern-based commands with automatic variable extraction for dynamic command handling.

Wake Word Detection

Hands-free activation with configurable wake words like "Hey Assistant" or "OK Computer", customizable timeout settings, and audio feedback.

Pattern Matching

Extract variables from voice commands automatically using simple pattern syntax like {variable} for dynamic command processing.

Audio Visualization

Real-time amplitude monitoring with waveform display, frequency bar visualization, and customizable rendering options.

Built-in Commands

Seven categories of pre-built commands including scrolling, zooming, clicking, form filling, content reading, theme control, and navigation.

Multi-language Support

Support for 50+ languages through the Web Speech API including en-US, es-ES, fr-FR, de-DE, ja-JP, zh-CN, and many more.


Built-in Commands

JSVoice includes pre-built voice commands for common web interactions:

Scrolling Commands:

  • scroll down - Scroll down 500 pixels
  • scroll up - Scroll up 500 pixels
  • scroll to bottom - Jump to page bottom
  • scroll to top - Jump to page top

Zoom Control:

  • zoom in - Increase zoom by 10%
  • zoom out - Decrease zoom by 10%
  • reset zoom - Reset to 100%

Element Interaction:

  • click [text] - Click element containing text
  • click button [text] - Click specific button

Form Filling:

  • type [value] in [field] - Fill input field
  • fill [value] in [field] - Alternative syntax

Content Reading:

  • read this page - Read entire page aloud
  • read this paragraph - Read nearest text block
  • read section [text] - Read specific section

Theme Control:

  • toggle dark mode - Switch between light and dark themes
  • dark mode on - Enable dark mode
  • dark mode off - Enable light mode

Navigation:

  • open new tab - Open blank tab
  • go to [website] - Open website (supports Google, YouTube, GitHub, etc.)

Advanced Features

Pattern Commands with Variables

Extract variables from voice commands for dynamic functionality:

voice.addPatternCommand('set volume to {level}', (args) => {
  const volume = parseInt(args.level);
  audioElement.volume = volume / 100;
  voice.speak(`Volume set to ${volume} percent`);
});

// User says: "set volume to 75"
// System extracts: { level: "75" }
// Result: Volume set to 75%

Wake Word Detection

Enable hands-free activation with wake words:

const voice = new JSVoice({
  wakeWord: 'hey assistant',
  wakeWordTimeout: 5000,
  onWakeWordDetected: (word) => {
    console.log('Wake word detected:', word);
  }
});

// User says: "hey assistant"
// System activates and listens
// User says: "scroll down"
// System executes command

Real-Time Audio Visualization

Display audio waveforms and frequency bars:

voice.startAmplitude((bars) => {
  // bars is array of normalized values (0-1)
  bars.forEach((value, index) => {
    const height = value * 100;
    updateVisualization(index, height);
  });
}, {
  mode: 'bars',
  barCount: 16
});

API Reference

Core Methods

start()
Start speech recognition and return a promise.

await voice.start();

stop()
Stop speech recognition immediately.

voice.stop();

toggle()
Toggle speech recognition on or off.

voice.toggle();

speak(text, lang)
Convert text to speech with optional language parameter.

voice.speak('Hello world');
voice.speak('Bonjour', 'fr-FR');

Command Methods

addCommand(phrase, callback)
Register an exact phrase command.

voice.addCommand('hello', () => {
  console.log('Hello command executed');
});

removeCommand(phrase)
Remove a registered command.

voice.removeCommand('hello');

addPatternCommand(pattern, callback)
Register a pattern-based command with variable extraction.

voice.addPatternCommand('search for {query}', (args) => {
  console.log('Searching for:', args.query);
});

removePatternCommand(pattern)
Remove a pattern command.

voice.removePatternCommand('search for {query}');

Visualization Methods

startAmplitude(callback, options)
Start real-time audio amplitude monitoring.

voice.startAmplitude((bars) => {
  console.log(bars);
}, { 
  mode: 'bars', 
  barCount: 8 
});

stopAmplitude()
Stop amplitude monitoring and clean up resources.

voice.stopAmplitude();

Properties

isListening
Returns true if currently listening for voice commands.

if (voice.isListening) {
  console.log('Listening for commands...');
}

microphoneAllowed
Returns true if microphone permission has been granted.

if (voice.microphoneAllowed) {
  console.log('Microphone access granted');
}

isApiSupported
Static property that returns true if Web Speech API is supported.

if (JSVoice.isApiSupported) {
  const voice = new JSVoice();
}

voiceFeedback
Returns the latest status message.

console.log(voice.voiceFeedback);

Configuration Options

const voice = new JSVoice({
  // Recognition settings
  continuous: true,              // Keep listening continuously
  interimResults: true,          // Show interim recognition results
  lang: 'en-US',                // Recognition language
  autoRestart: true,            // Auto-restart on error
  restartDelay: 500,            // Restart delay in milliseconds
  
  // Wake word settings
  wakeWord: null,               // Wake word phrase (e.g., 'hey assistant')
  wakeWordTimeout: 5000,        // Timeout after wake word in milliseconds
  
  // Initial commands
  commands: {},                 // Object of exact phrase commands
  patternCommands: [],          // Array of pattern commands
  
  // Event callbacks
  onSpeechStart: () => {},
  onSpeechEnd: () => {},
  onCommandRecognized: (phrase, raw, result) => {},
  onCommandNotRecognized: (raw) => {},
  onActionPerformed: (action, payload) => {},
  onMicrophonePermissionGranted: () => {},
  onMicrophonePermissionDenied: (error) => {},
  onWakeWordDetected: (word) => {},
  onError: (error) => {},
  onStatusChange: (message) => {}
});

Browser Support

Fully Supported:

  • Google Chrome 25+
  • Microsoft Edge 79+
  • Opera 27+

Partially Supported:

  • Safari 14.1+ (iOS 14.5+ required)

Not Supported:

  • Mozilla Firefox (Web Speech API not implemented)

Requirements:

  • HTTPS connection (required for microphone access)
  • User gesture to initiate (click or tap)
  • Microphone permission granted by user

Browser Detection:

if (JSVoice.isApiSupported) {
  // Initialize voice features
  const voice = new JSVoice();
} else {
  // Show fallback message
  console.warn('Voice commands not supported in this browser');
  alert('Please use Chrome, Edge, or Safari for voice features');
}

Examples

React Integration

import { useEffect, useRef } from 'react';
import JSVoice from 'jsvoice';

function VoiceComponent() {
  const voiceRef = useRef(null);

  useEffect(() => {
    voiceRef.current = new JSVoice({
      onStatusChange: (msg) => console.log(msg)
    });

    return () => voiceRef.current?.stop();
  }, []);

  return (
    <button onClick={() => voiceRef.current?.toggle()}>
      Toggle Voice Control
    </button>
  );
}

Vue Integration

<template>
  <button @click="toggleVoice">Toggle Voice Control</button>
</template>

<script>
import JSVoice from 'jsvoice';

export default {
  data() {
    return { voice: null };
  },
  mounted() {
    this.voice = new JSVoice({
      onStatusChange: (msg) => console.log(msg)
    });
  },
  methods: {
    toggleVoice() {
      this.voice.toggle();
    }
  },
  beforeUnmount() {
    this.voice?.stop();
  }
}
</script>

TypeScript

import JSVoice, { JSVoiceOptions } from 'jsvoice';

const options: JSVoiceOptions = {
  lang: 'en-US',
  continuous: true,
  onCommandRecognized: (phrase, raw, result) => {
    console.log(`Recognized: ${phrase}`);
  }
};

const voice = new JSVoice(options);

Use Cases

Accessibility

Enable hands-free navigation for users with disabilities:

voice.addCommand('next page', () => {
  window.location.href = getNextPageUrl();
});

voice.addCommand('previous page', () => {
  window.history.back();
});

voice.addCommand('read content', () => {
  const text = document.body.innerText;
  voice.speak(text);
});

E-Commerce

Create voice-controlled shopping experiences:

voice.addPatternCommand('add {quantity} {product} to cart', (args) => {
  addToCart(args.product, parseInt(args.quantity));
  voice.speak(`Added ${args.quantity} ${args.product} to your cart`);
});

voice.addCommand('checkout', () => {
  navigateToCheckout();
  voice.speak('Proceeding to checkout');
});

Smart Home Dashboard

Control IoT devices with voice commands:

voice.addPatternCommand('turn {device} {state}', (args) => {
  controlDevice(args.device, args.state);
  voice.speak(`Turning ${args.device} ${args.state}`);
});

voice.addPatternCommand('set {device} to {value}', (args) => {
  setDeviceValue(args.device, args.value);
  voice.speak(`Setting ${args.device} to ${args.value}`);
});

Gaming

Add voice commands to games:

voice.addCommand('attack', () => player.attack());
voice.addCommand('defend', () => player.defend());
voice.addCommand('use potion', () => player.usePotion());
voice.addCommand('open inventory', () => ui.showInventory());

Documentation

Complete Guides:

Additional Resources:


Performance

Bundle Size: 32KB minified and gzipped

Dependencies: Zero external libraries

Initialization: Under 100ms startup time

Memory: Efficient with automatic resource cleanup

Optimization:

  • Tree-shaking compatible for smaller bundles
  • Source maps included for debugging
  • Multiple build formats (ESM, CJS, UMD)
  • Lazy loading support

Security and Privacy

Data Handling:

  • All processing happens in the browser
  • No data sent to external servers
  • No data collection or storage
  • No tracking or analytics

Permissions:

  • Explicit user consent required for microphone
  • HTTPS required for security
  • Permissions revocable anytime
  • Transparent permission requests

Contributing

We welcome contributions from the community!

How to Contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Guidelines:

  • Follow existing code style
  • Add documentation for new features
  • Include examples where helpful
  • Write clear commit messages

See CONTRIBUTING.md for detailed guidelines.


Support

Get Help:

Report Issues:

  • Bug reports via GitHub Issues
  • Feature requests via GitHub Discussions
  • Security issues via email

License

MIT License - see LICENSE file for details.

Free for commercial and personal use.


Links


Acknowledgments

Built by the open-source community.

Thanks to all contributors who helped improve JSVoice.


Made for the JavaScript community

⬆ Back to Top