Search code examples
javascripthtmlspeech-recognitionspeech-to-text

Web Speech Recognition code not transcribing speech


I'm trying to use HTML5 Web Speech API's Speech Recognition.

I can't figure out why this code is not working. It is triggering the permission for requesting access to the microphone, but when I speak nothing is transcribed.

When I look in the console, there are no errors, but the console.log that happens when the speech recognition is stopped is triggered.

I think it is stopping prematurely.

Does anyone know what is going on and why it is not working?

Here is the JS:

It depends on webspeech.js, which is included in the jsfiddle.

Here is the JS Fiddle: http://jsfiddle.net/2sMXZ/3/

Here is the implementation code:

var reco = new WebSpeechRecognition;
$('#mic').click(function(){
    $(this).toggleClass('red');
    reco.toggleStartStop();
});
var interim_transcript = '';
reco.recognition.onresult = function(event){
    for(var i = event.resultIndex; i<event.results.length; ++i){
        if(event.results[i].isFinal) reco.stop();
        else interim_transcript += event.results[i][0].transcript;
    }
}
$('#interim_span').html(interim_transcript);
console.log(interim_transcript);
reco.recognition.onend = function(e){
    //$('#mic').removeClass('red');
    console.log('done');
}

Solution

  • First, $('#interim_span').html(interim_transcript) is called every interim results are emitted.

    Second, when event.results[i].isFinal is true, it has a result as well.

    Try

    var reco = new WebSpeechRecognition;
    $('#mic').click(function(){
        $(this).toggleClass('red');
        reco.toggleStartStop();
    });
    var interim_transcript = '';
    reco.recognition.onresult = function(event){
        for(var i = event.resultIndex; i<event.results.length; ++i){
            if(event.results[i].isFinal) reco.stop();
            interim_transcript += event.results[i][0].transcript;
        }
        $('#interim_span').html(interim_transcript);
        console.log(interim_transcript);
    }
    
    reco.recognition.onend = function(e){
        //$('#mic').removeClass('red');
        console.log('done');
    }