语音识别、断言错误 "Source must be an audio source"

SpeechRecognition, AssertionError "Source must be an audio source"

这是我的代码:

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as source:
    print('Say Something')
    audio = r.listen(source)
    voice_data = r.record(audio)
    print(voice_data)

当我在终端上键入 "python main.py" 并启动程序时,它开始收听但听不懂我说的话。我尝试使用 adjust_for_ambient_noise() 而不是 listen() 但它也没有改变任何东西。

我正在使用 macOS Catalina 和 Python 3.8.1.

这是我得到的错误:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    voice_data = r.record(audio)
  File "/Users/sefailyasoz/PycharmProjects/SpeechAssistant/venv/lib/python3.8/site-packages/speech_recognition/__init__.py", line 483, in record
    assert isinstance(source, AudioSource), "Source must be an audio source"
AssertionError: Source must be an audio source 

这是我用adjust_for_ambient_noise()时得到的,如果我用listen,它不会结束,它只是听,我用Ctrl+C结束.

您在这里使用了函数record(),该函数用于从文件中捕获数据,在捕获麦克风输入时应改用listen() 函数。

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as source:
    print('Say Something')
    audio = r.listen(source)
    print(audio) #This is just a speech_recognition.AudioData object
    text = r.recognize_google(audio) #Speech to text google recognizer
    print(text) #This is what you actually said

嗯,我稍微改变了我的功能

def record_audio(ask=False):
    with sr.Microphone() as source:
        if ask:
            turkishSiri_speak(ask)
        audio = r.listen(source)
        voice_data = ''
        try:
            voice_data = r.recognize_google(audio , language='tr-TR')
        except sr.UnknownValueError:
            turkishSiri_speak('Ne söylediğini anlayamadım')
        except sr.RequestError:
            turkishSiri_speak('Google konuşma servisinde bir problem var')
        return voice_data

但最大的问题是 macOS 问题,我必须允许 pycharm 或 visual studio 代码才能使用我的麦克风。在更改功能之前它已经在给予许可后工作