Search code examples
pythonspeech-recognitionspeech-to-textsys

Output of Speech Recognition (Python)


I am working on a project with speech recognition module and due to my different language, I want to save on text file so I can read and have proper output; but when I tried sys module to save the file it came with some errors. If you help me to fix this I`ll be appreciate This is my code:

import speech_recognition as sr 
import sys

r = sr.Recognizer()
print('How can I help you?')
def my_first_sr():
    while True:
        try:
            with sr.Microphone() as mic:
                r.adjust_for_ambient_noise(mic)
                audio = r.listen(mic)
                text = r.recognize_google(audio, language = 'fa-IR')
            print(text)
        except sr.UnknownValueError:
            print('I didn`t understand!')

        except sr.RequestError:
            print('Sorry my service is down')


my_first_sr()
output = open('Speech Recognition.txt', 'w')
sys.stdout = output
print(text)
output.close()

Solution

  • You have to write the text to the file output:

    import speech_recognition as sr 
    
    r = sr.Recognizer()
    print('How can I help you?')
    def my_first_sr():
        while True:
            try:
                with sr.Microphone() as mic:
                    r.adjust_for_ambient_noise(mic)
                    audio = r.listen(mic)
                    text = r.recognize_google(audio, language = 'fa-IR')
    
                print(text)
    
                output = open('Speech Recognition.txt', 'w')
                output.write(text)#Write the text to the file
                output.close()
    
            except sr.UnknownValueError:
                print('I didn`t understand!')
    
            except sr.RequestError:
                print('Sorry my service is down')
    
    
    my_first_sr()