为什么Python语音识别模块不工作?

gdrx4gfi  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(144)

我试图使用我的麦克风在python中创建文本到语音模块,但是当我运行程序时,它抛出错误。下面是我的代码:

import pyttsx3
import speech_recognition as sr
import webbrowser
import datetime
import pyjokes

def sptext():
    # Create a recognizer instance
    recognizer = sr.Recognizer()

    # Use the default microphone as the audio source
    with sr.Microphone() as source:
        print("Listening...")

        try:
            # Adjust for ambient noise before listening
            recognizer.adjust_for_ambient_noise(source)

            audio = recognizer.listen(source)

            # Use Google Speech Recognition to transcribe the audio to text
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand what you said.")
        except sr.RequestError as e:
            print(f"Request error: {e}")
        
        try:
            # Close the audio stream
            source.stream.close()
        except AttributeError:
            pass

sptext()

我得到的错误是

During handling of the above exception, another exception occurred:   

Traceback (most recent call last):  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 68, in <module>
    sptext()  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 44, in sptext
    with sr.Microphone() as source:
  File "C:\Users\Asus\AppData\Roaming\Python\Python311\site-packages\speech_recognition\__init__.py", line 189, in __exit__
    self.stream.close()
    ^^^^^^^^^^^^^^^^^AttributeError: 'NoneType' object has no attribute 'close'

尝试使用speechRecognition模块在Python中创建一个语音到文本项目,但不知何故,我不知道我的代码有什么问题?

hmae6n7t

hmae6n7t1#

当你使用with ... as ...模式时,你不必使用.close()。更多信息,请参见this answer

6ovsh4lw

6ovsh4lw2#

当你使用'with'语句时,麦克风流在你离开'with'块时自动关闭。不需要stream.close()语句。修改的代码:

import pyttsx3
import speech_recognition as sr
import webbrowser
import datetime
import pyjokes

def sptext():
    # Create a recognizer instance
    recognizer = sr.Recognizer()

    # Use the default microphone as the audio source
    with sr.Microphone() as source:
        print("Listening...")

        try:
            # Adjust for ambient noise before listening
            recognizer.adjust_for_ambient_noise(source)

            audio = recognizer.listen(source)

            # Use Google Speech Recognition to transcribe the audio to text
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand what you said.")
        except sr.RequestError as e:
            print(f"Request error: {e}")
   
sptext()

相关问题