Reputation: 9
I have code to convert voice to written text, I want to save the written text after it's converted to files that can be accessed later, how do I do it in the following code?
import speech_recognition as sr
def main():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print("Please say something to start recording the lecture ")
audio = r.listen(source)
print("Recognizing Now .... ")
# recognize speech using google
try:
print("You have said \n" + r.recognize_google(audio))
print("Audio Recorded Successfully \n ")
except Exception as e:
print("Error : " + str(e))
# write audio
with open("recorded.wav", "wb") as f:
f.write(audio.get_wav_data())
if __name__ == "__main__":
main()
I tried to create another python file and run it as .txt but it saves the code not recoreded one
Upvotes: 0
Views: 773
Reputation: 1143
In your def main():
function you need to open a text file using open()
, something similar to as shown:
transcript = open('transcript.txt', 'w')
after that where you are using print("You have said \n" + r.recognize_google(audio))
You have to write the data coming from r.recognize_google(audio)
to the above transcript.txt
text file using transcript
file descriptor
transcript.write(r.recognize_google(audio))
Also you need to make sure to close the open file descriptor using transcript.close()
Modified your code slightly to show how you can do it
import speech_recognition as sr
def main():
transcript = open('transcript.txt', 'w')
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print("Please say something to start recording the lecture ")
audio = r.listen(source)
print("Recognizing Now .... ")
# recognize speech using google
try:
print("You have said \n" + r.recognize_google(audio))
transcript.write(r.recognize_google(audio))
print("Audio Recorded Successfully \n ")
except Exception as e:
print("Error : " + str(e))
# write audio
with open("recorded.wav", "wb") as f:
f.write(audio.get_wav_data())
f.close()
transcript.close()
if __name__ == "__main__":
main()
Upvotes: 1