Spaces:
Sleeping
Sleeping
import streamlit as st | |
import streamlit.components.v1 as components | |
# HTML and JavaScript for Speech Recognition using webkitSpeechRecognition | |
speech_recognition_html = """ | |
<html> | |
<body> | |
<button onclick="startRecognition()">Start Speech Recognition</button> | |
<p id="output">Speak something...</p> | |
<script> | |
// Check if the browser supports speech recognition | |
if (!('webkitSpeechRecognition' in window)) { | |
document.getElementById('output').textContent = "Speech recognition not supported in this browser."; | |
} | |
var recognition = new webkitSpeechRecognition(); | |
recognition.continuous = false; // Stops after speech input | |
recognition.interimResults = true; | |
recognition.lang = 'en-US'; // Set language for recognition (English) | |
recognition.onresult = function(event) { | |
var transcript = event.results[event.resultIndex][0].transcript; | |
document.getElementById('output').textContent = transcript; | |
// Send transcript back to Streamlit using postMessage | |
window.parent.postMessage({func: 'update_output', transcript: transcript}, '*'); | |
}; | |
recognition.onerror = function(event) { | |
console.error("Speech recognition error", event.error); | |
document.getElementById('output').textContent = "Error in recognition"; | |
}; | |
function startRecognition() { | |
recognition.start(); | |
} | |
</script> | |
</body> | |
</html> | |
""" | |
# Streamlit UI | |
st.title("Speech-to-Text Demo") | |
st.write("Click the button below and start speaking. The recognized text will be shown here:") | |
# Display the HTML with the embedded speech recognition | |
components.html(speech_recognition_html, height=200) | |
# Output area where the recognized speech will be displayed | |
output = st.empty() | |
# This is where the recognized text will be shown on the Streamlit side | |
st.write("Recognized Text:") | |
transcript = st.text_area("Transcript:", "", height=150) | |
# Listen for postMessage events from the iframe to update the text area | |
components.html(""" | |
<script> | |
window.addEventListener('message', function(event) { | |
if (event.data.func === 'update_output') { | |
document.getElementById('output').textContent = event.data.transcript; | |
// Update the Streamlit text area with the transcript | |
window.parent.postMessage({func: 'update_text_area', text: event.data.transcript}, '*'); | |
} | |
}); | |
</script> | |
""", height=0) | |