语音识别(语音转换为文本)



我有代码转换语音到书面文本,我想保存书面文本后,它被转换为文件,可以访问以后,我如何做到这一点在下面的代码?

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()

我尝试创建另一个python文件并以。txt的形式运行它,但它保存了未记录的代码

def main():函数中,您需要使用open()打开一个文本文件,类似于如下所示:

transcript = open('transcript.txt', 'w')

之后,您使用print("You have said n" + r.recognize_google(audio))
您必须使用transcript文件描述符将来自r.recognize_google(audio)的数据写入上述transcript.txt文本文件

transcript.write(r.recognize_google(audio))

您还需要确保使用transcript.close()

关闭打开的文件描述符稍微修改了一下代码,以展示如何做到这一点

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()

最新更新