Automatic recognition start

by velo_ninja

HTML

<!DOCTYPE html>
<html>

<head>
    <title>Microphone Control</title>
    <style>
        #result {
            border: 2px solid black;
            height: 200px;
            border-radius: 3px;
            font-size: 14px;
            white-space: pre-wrap;
            overflow-y: auto;
            margin-bottom: 10px;
        }

        button {
            margin-top: 10px;
        }
    </style>
</head>

<body onload="toggleMicrophone();" style="background-color: lightgray;">
    <div id="result"></div>
    <audio id="audioPlayer" controls style="display: none;"></audio>
    <button onclick="sendData()">Send Data</button>

    <script>
        function init() {
            // when a message is received from the page code
            window.onmessage = (event) => {
                if (event.data) {
                    console.log("HTML Code Element received a message!");
                    insertMessage(event.data);
                }
            }
        }

        let recognition;
        let isRecording = false;
        let resultDiv = document.getElementById("result");
        let audioPlayer = document.getElementById("audioPlayer");

        async function toggleMicrophone() {
            if (!isRecording) {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    handleSuccess(stream);
                } catch (e) {
                    console.error('Error accessing microphone:', e);
                    resultDiv.innerText = "Error accessing microphone. Please check your browser settings.";
                }
            } else {
                stopRecording();
            }
        }

        function handleSuccess(stream) {
            recognition = new webkitSpeechRecognition();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.lang = "en-US";

            recognition.onstart = function () {
               ...