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 🙏

© 2025 – Pkg Stats / Ryan Hefner

preset-mic

v1.0.4

Published

Biblioteca para realizar a transcrição de áudio em texto no navegador, pronta para uso, com configuração otimizada para voz.

Readme

PresetMic

Biblioteca JavaScript para gravação de áudio no navegador, pronta para uso, sem necessidade de configuração.

Principais características

  • Usa MediaRecorder e getUserMedia com sampleRate 44100Hz, mono, Opus (audio/webm)
  • API simples: start, pause, resume, stop
  • Exporta áudio como Blob ou ArrayBuffer
  • Fornece eventos/callbacks para status e dados
  • Compatível com React, Vue, Angular e JS puro

Como testar localmente

  1. Instale a biblioteca via npm:
npm install preset-mic
  1. Importe e utilize a classe conforme os exemplos abaixo.

Exemplo de uso em JavaScript puro

import PresetMic from 'preset-mic';
// Para texto parcial em tempo real (padrão)
const mic = new PresetMic({ lang: 'pt-BR' });

mic.on('transcription', (texto) => {
  // Chamado em tempo real enquanto fala
  console.log('Transcrição parcial/final:', texto);
});
mic.on('error', (err) => console.error('Erro:', err));

// Para iniciar
await mic.start();
// Para parar: mic.stop();

// Para receber apenas o texto final ao parar:
const micFinal = new PresetMic({ lang: 'en-US', onlyFinal: true });
let textoFinal = '';
micFinal.on('transcription', (texto) => {
  // Só será chamado ao parar (micFinal.stop())
  textoFinal = texto;
  console.log('Transcrição final:', textoFinal);
});
await micFinal.start();
// ...fale algo...
micFinal.stop(); // textoFinal terá o texto completo

Exemplo de uso em React

import React, { useRef, useState } from 'react';
import PresetMic from 'preset-mic';

export default function AudioRecorder() {
  const micRef = useRef(null);
  const [transcript, setTranscript] = useState('');
  const [isRecording, setIsRecording] = useState(false);


  // Exemplo: texto parcial/final em tempo real (padrão)
  const start = async () => {
    if (!micRef.current) {
      micRef.current = new PresetMic({ lang: 'pt-BR' });
      micRef.current.on('transcription', (texto) => setTranscript(texto));
      micRef.current.on('start', () => setIsRecording(true));
      micRef.current.on('stop', () => setIsRecording(false));
    }
    setTranscript('');
    await micRef.current.start();
  };

  // Para texto final apenas ao parar:
  // const start = async () => {
  //   if (!micRef.current) {
  //     micRef.current = new PresetMic({ lang: 'en-US', onlyFinal: true });
  //     micRef.current.on('transcription', (texto) => setTranscript(texto)); // Só será chamado ao parar
  //     micRef.current.on('start', () => setIsRecording(true));
  //     micRef.current.on('stop', () => setIsRecording(false));
  //   }
  //   setTranscript('');
  //   await micRef.current.start();
  // };

  const stop = () => {
    if (micRef.current) {
      micRef.current.stop();
    }
  };

  return (
    <div>
      <button onClick={start} disabled={isRecording}>Falar</button>
      <button onClick={stop} disabled={!isRecording}>Parar</button>
      {isRecording && <p>Ouvindo...</p>}
      <p>Transcrição: {transcript}</p>
    </div>
  );
}

Exemplo de uso em Vue 3

<template>
  <div>
    <button @click="start" :disabled="isRecording">Falar</button>
    <button @click="stop" :disabled="!isRecording">Parar</button>
    <p v-if="isRecording">Ouvindo...</p>
    <p>Transcrição: {{ transcript }}</p>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import PresetMic from 'preset-mic';

const mic = ref(null);
const transcript = ref('');
const isRecording = ref(false);

// Exemplo: texto parcial/final em tempo real (padrão)
const start = async () => {
  if (!mic.value) {
    mic.value = new PresetMic({ lang: 'pt-BR' });
    mic.value.on('transcription', (texto) => transcript.value = texto); // Chamado em tempo real
    mic.value.on('start', () => isRecording.value = true);
    mic.value.on('stop', () => isRecording.value = false);
  }
  transcript.value = '';
  await mic.value.start();
};
const stop = () => mic.value && mic.value.stop();

// Para texto final apenas ao parar:
// const start = async () => {
//   if (!mic.value) {
//     mic.value = new PresetMic({ lang: 'en-US', onlyFinal: true });
//     mic.value.on('transcription', (texto) => transcript.value = texto); // Só será chamado ao parar
//     mic.value.on('start', () => isRecording.value = true);
//     mic.value.on('stop', () => isRecording.value = false);
//   }
//   transcript.value = '';
//   await mic.value.start();
// };
</script>

Observação para uso com Vue + TypeScript

Se você estiver usando Vue com TypeScript, adicione o seguinte arquivo (por exemplo, src/shims-vue.d.ts):

declare module '*.vue' {
  import { DefineComponent } from 'vue';
  const component: DefineComponent<{}, {}, any>;
  export default component;
}

Isso é necessário para que o TypeScript reconheça arquivos .vue como módulos válidos.

Exemplo de uso em Angular

// audio-recorder.component.ts
import { Component } from '@angular/core';
import PresetMic from 'preset-mic';

@Component({
  selector: 'app-audio-recorder',
  template: `
    <button (click)="start()">Gravar</button>
    <button (click)="pause()">Pausar</button>
    <button (click)="resume()">Retomar</button>
    <button (click)="stop()">Parar</button>
  `
})
export class AudioRecorderComponent {
  mic: any;

  async start() {
    if (!this.mic) {
      this.mic = new PresetMic();
      this.mic.on('stop', (blob: Blob) => {
        const url = URL.createObjectURL(blob);
        // Faça algo com a URL
      });
    }
    await this.mic.start();
  }
  pause() { this.mic && this.mic.pause(); }
  resume() { this.mic && this.mic.resume(); }
  stop() { this.mic && this.mic.stop(); }
}

Melhores práticas e recomendações

  • Grave em ambiente silencioso para melhor qualidade.
  • Use microfone de boa qualidade se possível.
  • O áudio é exportado em formato Opus (audio/webm), ideal para voz.
  • Não é necessário configurar nada: basta instanciar e usar.

Como contribuir

  1. Faça um fork do projeto.
  2. Crie uma branch: git checkout -b minha-feature.
  3. Faça suas alterações e commit: git commit -m 'Minha nova feature'.
  4. Envie para o seu fork: git push origin minha-feature.
  5. Abra um Pull Request.

Licença

MIT


Como clonar e instalar dependências

git clone https://github.com/seu-usuario/preset-mic.git
cd preset-mic
npm install

Sinta-se à vontade para abrir issues e contribuir!