【问题标题】:Voice Recognition (converting voice to text)语音识别(将语音转换为文本)
【发布时间】:2023-01-09 18:32:00
【问题描述】:

我有将语音转换为书面文本的代码,我想在将书面文本转换为文件后保存起来以便以后访问,我该如何在以下代码中执行?

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 运行,但它保存了未重新编码的代码

【问题讨论】:

    标签: python linux voice-recognition


    【解决方案1】:

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

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

    在那之后你在哪里使用print("You have said " + 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 
    " + r.recognize_google(audio))
                transcript.write(r.recognize_google(audio))
                print("Audio Recorded Successfully 
     ")
            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()
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多