Search code examples
pythonspeech-to-textgoogle-speech-api

Google Speech to Text - Can't write output to text file


I am attempting to write to a text file. It just seems to fail every time. I can write .write("test") but writing the google transcription output to file seems to fail.

Any advice would be greatly appreciated.

import speech_recognition as sr

from os import path

from pprint import pprint

audio_file = path.join(path.dirname(path.realpath(__file__)), "RobertP.wav")

r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
    audio = r.record(source)

try:
    txt = r.recognize_google(audio, show_all=True)
    pprint (txt)

except:
    print("Didn't work.")

try:
    f = open("tester.txt", "w+")
    f.write(txt)
    f.close()
except:
    print("Couldn't write to file")```

Solution

  • It Looks like txt is not a string. You can try to convert it to a string with str(txt).

    btw: It's better to remove the try/except for testing reasons to get the error. After the program works you can add it again,.