0

I'm using web speech api

https://www.google.com/intl/en/chrome/demos/speech.html

but mic automatically closes after some seconds but i have to close mix only when the user clicks on close buttons.

Any solution to resolve this issue. Thanks

user3653474
  • 3,393
  • 6
  • 49
  • 135

1 Answers1

1

You should mark the recognition service as continuous and maybe start the recorder again if it stops after the timeout when there is no activity.

 <button onclick='toggleRecording()'>Toggle recorder</button>
 <div id='results'></div>
 <script>
    window.SpeechRecognition = window.SpeechRecognition ||
    window.webkitSpeechRecognition;

    let recognition = new window.SpeechRecognition()
    let recording = false;
    let results = null;

    recognition.continuous = true;

    function toggleRecording() {
        if(recording) {
            recognition.onend = null;
            recognition.stop();
            recording = false;

            // Printing all results we got so far.
            if(results) {
                let resultsDiv = document.getElementById('results')
                for(let i=0; i<results.length; ++i)
                    resultsDiv.innerHTML = resultsDiv.innerHTML + results.item(i)[0].transcript
            }
        } else {
            recognition.onend = onEnd;
            recognition.start();
            recording = true;
        }
    }

    function onEnd() {
        console.log('Speech recognition has stopped. Starting again ...');
        recognition.start();
    }


    function onSpeak(e) {
        results = e.results;
        console.log(e.results[e.results.length-1][0].transcript);
    }

    recognition.addEventListener('result', onSpeak);

</script>
limekin
  • 1,934
  • 1
  • 12
  • 15
  • Thanks for the answer i have checked, after giving permission to mic after sometime it again ask for permission but i want to continuously record till the user pressed stop button and then print the whole session result can you please update your answer – user3653474 Jan 10 '22 at 14:48
  • @user3653474 Ah yes, that's intended behavior when you are not running the script on a page not served over HTTPS or localhost. https://developers.google.com/web/updates/2013/01/Voice-Driven-Web-Apps-Introduction-to-the-Web-Speech-API – limekin Jan 10 '22 at 15:03
  • Okay how will i print the final result that is recorded in one session, from starting the recording to end by pressing the button – user3653474 Jan 10 '22 at 15:14
  • @user3653474 I have updated the answer so that it prints all results obtained until the recording is stopped. – limekin Jan 10 '22 at 15:29
  • 1
    okay Thanks it's working – user3653474 Jan 10 '22 at 15:35
  • Can you please answer my question i'm trying to integrate webspeech in angular but it is not working Question link : https://stackoverflow.com/questions/70677003/integrating-webspeech-in-angular – user3653474 Jan 12 '22 at 06:49