Created
February 19, 2024 13:04
-
-
Save baztian/edf5d1256d59fdf523be4e873c0f5299 to your computer and use it in GitHub Desktop.
Speech recognition and insert at cursor position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
import sys | |
import speech_recognition as sr | |
def get_audio_text(language=None): | |
language = language or "en-US" | |
recognizer = sr.Recognizer() | |
with sr.Microphone() as source: | |
print("Say something:") | |
audio = recognizer.listen(source) | |
try: | |
text = recognizer.recognize_google(audio, language=language) | |
return text | |
except sr.UnknownValueError: | |
print("Could not understand audio.") | |
except sr.RequestError as e: | |
print(f"Error with the speech recognition service; {e}") | |
return None | |
def insert_text_at_cursor(text): | |
subprocess.run(["xdotool", "type", "--clearmodifiers", text]) | |
if __name__ == "__main__": | |
# If a language code is provided, use it; otherwise, use the default | |
# e.g. de-DE | |
if len(sys.argv) > 1: | |
language = sys.argv[1] | |
else: | |
language = None | |
spoken_text = get_audio_text(language=language) | |
if spoken_text: | |
insert_text_at_cursor(spoken_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ChatGPT prompt:
Preconditions
Execute for
en-US
by just executing. Provide other locales such asde-DE
as first parameter.