'How to trigger speech recognition with tkinter hold button press?

When I press AND hold a tkinter button I would like to trigger a speech recognition function and would like the speech recognition to keep listening while holden the button. When I release the button I want the speech recognition to end and stop listening.

import tkinter as tk
import speech_recognition as sr #recognise speech

class SpeechRecognition():
    def __init__(self):
        self.r = sr.Recognizer() #initialize recognizer that is responsible for recognizing the speech
            
    # listen for audio and convert it to text:
    def record_audio(self, ask=False):
        with sr.Microphone() as source: # microphone as source
            if ask: 
                print(ask)
            self.r.adjust_for_ambient_noise(source) # recognize much clearly, by reducing background noise
            audio = self.r.listen(source) # listen for the audio via source

            voice_data = ''
            try:
                voice_data = self.r.recognize_google(audio, language='sv-SE') # convert audio to text
            except sr.UnknownValueError: # error: recognizer does not understand
                print('Hörde inte det') 
            except sr.RequestError: # error: recognizer is not connected
                print('Ledsen, tjänsten är nere')
            print(f">> {voice_data}") # print what user said
            return voice_data

class MainApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs) 
        self.parent = parent
        ...

        self.textbox = tk.Text(main_frame, width=500, height=10, wrap='word')
        self.textbox.pack(padx=8, pady=(0,8))

        
        self.speech_to_text_button = tkm.Button(main_frame, text="Speech 
        to text", padx=5, pady=10)
        self.speech_to_text_button.pack()
        self.speech_to_text_button.bind("<Button>",  lambda event, textbox=self.textbox: 
        self.speech_recognition(event, textbox))



    def speech_recognition(self, event, textbox):
        self.speechObj = SpeechRecognition()
        voice_data = self.speechObj.record_audio()
        textbox.insert('end', voice_data)

The speech recognition starts to listen when I press the button. But I want it to listen only when I hold the button and then stop listen when I release the button. How can I achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source