Skip to content

Instantly share code, notes, and snippets.

@WilfredLemus
Forked from Kolesias123/voice.js
Last active August 29, 2015 14:08
Show Gist options
  • Save WilfredLemus/a9c1c6c279cb35881ecc to your computer and use it in GitHub Desktop.
Save WilfredLemus/a9c1c6c279cb35881ecc to your computer and use it in GitHub Desktop.
/**
* Módulo: Voice
* Funciones de comandos por voz en HTML 5.
*/
Voice =
{
Speech: null, // webkitSpeechRecognition
Recognizing: false, // ¿Estamos intentando reconocer la voz ahora mismo?
LastCommand: '', // Último comando
// ¿En vez de comandos usamos este módulo para dictar en un input?
InputElement: null,
InputText: '',
// Comandos registrados.
Commands: {},
/**
* Inicializa la API ( Debe llamarse antes de todo )
*/
Init: function()
{
var Speech = new webkitSpeechRecognition();
Speech.continuous = true;
Speech.interimResults = true;
// Al empezar a reconocer.
Speech.onstart = function()
{
Voice.Recognizing = true;
};
// Al tener un error ( No se pudo conectar con Google, no hay microfono, etc )
Speech.onerror = function()
{
console.error('[VOICE] ' + event.error);
Voice.OnError(event.error);
};
// Al terminar de reconocer.
Speech.onend = function()
{
Voice.Recognizing = false;
};
// Definimos la API ya creada.
Voice.Speech = Speech;
},
/**
* Activa el reconocimiento de voz.
*
* @param {string} inputElement Identificación hacia un input
*/
Enable: function(inputElement)
{
// Comandos por voz.
if ( inputElement == null || inputElement == undefined )
Voice.Speech.onresult = Voice.Process;
// Dictado hacia un <input>
else
{
Voice.Speech.onresult = Voice.ProcessInput;
Voice.InputElement = inputElement;
Voice.InputText = $(inputElement).val();
}
Voice.OnReady();
Voice.Start();
},
/**
* Empieza el reconocimiento de voz
*/
Start: function()
{
if ( Voice.Recognizing )
return;
Voice.Speech.start();
},
/**
* Para el reconocimiento de voz.
*/
Stop: function()
{
if ( !Voice.Recognizing )
return;
Voice.Speech.stop();
},
/**
* Empieza o para el reconocimiento de voz.
*/
Toggle: function()
{
if ( Voice.Recognizing )
{
Voice.Stop();
return;
}
Voice.Start();
},
/**
* Establece el idioma para el reconocimiento de voz.
*
* @param {string} lang [description]
*/
SetLang: function(lang)
{
Voice.Speech.lang = lang;
},
/**
* Establece un nuevo comando de voz.
*
* @param {String} name Comando de voz ( Ejemplo: reproducir música [¡En minusculas!] )
* @param {Function} callback Función que se ejecutará al recibir el comando de voz.
*/
Set: function(name, callback)
{
name = name.toLowerCase();
Voice.Commands[name] = callback;
},
/**
* Procesa el reconocimiento de voz.
*
* @param {[type]} e Resultados
*/
Process: function(e)
{
// Algo sucedio mal.
if ( typeof(e.results) == 'undefined' )
{
Voice.Speech.onend = null;
Voice.Speech.stop();
console.error('[VOICECOMMAND] Error: ' + e);
return;
}
// Comando que se reconocio finalmente.
var FinalSpeech = '';
// Obtenemos los resultados del reconocimiento.
for ( var i = e.resultIndex; i < e.results.length; ++i )
{
// Google lo detecto como "Reconocimiento final"
if ( e.results[i].isFinal )
FinalSpeech += e.results[i][0].transcript;
}
// Se detecto algo.
if ( FinalSpeech != '' )
{
FinalSpeech = FinalSpeech.toLowerCase(); // Minusculas
var Callback = Voice.Commands[FinalSpeech]; // Buscamos la función que activa este comando de voz.
// ¡Existe! La ejecutamos.
if ( typeof(Callback) == 'function' )
Callback();
// Hemos detectado esto...
Voice.OnSpeech(FinalSpeech);
}
},
ProcessInput: function(e)
{
if ( typeof(e.results) == 'undefined' )
{
Voice.Speech.onend = null;
Voice.Speech.stop();
console.error('[VOICE] Error: ' + e);
return;
}
var FinalSpeech = '';
var TmpSpeech = '';
for ( var i = e.resultIndex; i < e.results.length; ++i )
{
if ( e.results[i].isFinal )
FinalSpeech += e.results[i][0].transcript;
else
TmpSpeech += e.results[i][0].transcript;
}
if ( FinalSpeech != '' )
{
FinalSpeech = ucfirst(Voice.InputText + trim(strtolower(FinalSpeech)));
$(Voice.InputElement).val(FinalSpeech + ' ');
//$(Voice.InputElement).removeClass('tmp-speech');
$(Voice.InputElement).removeAttr('disabled');
Voice.InputText = FinalSpeech;
Voice.OnSpeech(FinalSpeech);
}
else
{
$(Voice.InputElement).val(Voice.InputText + TmpSpeech);
//$(Voice.InputElement).addClass('tmp-speech');
$(Voice.InputElement).attr('disabled', '');
}
},
/**
* Al estar listo.
*/
OnReady: function()
{ },
/**
* Al detectar un comando de voz.
*
* @param {string} speech Comando de voz
*/
OnSpeech: function(speech)
{ },
/**
* Al obtener un error.
*
* @param {[type]} e [description]
*/
OnError: function(e)
{ },
};
// Iniciamos
Voice.Init();
console.log('[KERNEL] Se ha cargado el módulo VOICE.');
/**
* Ejemplos
*/
// Al decir: mostrar reproductor
Voice.Set('mostrar reproductor', function()
{
$('#player').fadeIn('slow');
});
// Al decir: ocultar reproductor
Voice.Set('ocultar reproductor', function()
{
$('#player').fadeOut('slow');
});
// Al decir: hola
Voice.Set('hola', function()
{
alert('¡Hola! ¿Como estas?');
});
// Al dar clic sobre un boton para empezar el reconocimiento.
$('#start').on('click', function()
{
Voice.Enable();
});
// Al detectar algo.
Voice.OnSpeech = function(speech)
{
console.log('[VOICE] Hemos detectado que ha dicho: ' + speech);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment