Search code examples
pythonspeech-recognitiongoogle-speech-api

Speech Recognition Library in Python always returns same string


I'm trying to use Google Speech recognition, My problem is that after saying something into microphone, results are always same.

My Function looks like this

def RecordAudio():
    import speech_recognition as sr

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)

    # Speech recognition using Google Speech Recognition
    try:
        print("You said: " + r.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

    return audio

When I'm trying to get data

data = RecordAudio()

Data is always equals to this speech_recognition.AudioData object at 0x111a8b358

But what is strange for me is that, when this code is in one file, without function and without returning result, in that time this works.

For example I've test.py file

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Say something!")
    audio = r.listen(source)

# Speech recognition using Google Speech Recognition
try:
    print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

This is working but first example not.

Any idea what's happening ?


Solution

  • I Solved it.

    I think that my problem was, that this function

    audio = r.listen(source)
    

    returns AudioData and when I was printing it thats why it was speech_recognition.AudioData object at 0x111a8b358

    To recognize it we must return

    return r.recognize_google(audio)
    

    It will return real string and not AudioData.

    If somebody will have same problem,hope it helps.