📜  Python语音识别简介

📅  最后修改于: 2020-09-04 05:14:02             🧑  作者: Mango

顾名思义,语音识别是指人类语音的自动识别。语音识别是人机交互领域中最重要的任务之一。如果您曾经与Alexa进行过交互或曾经命令Siri完成任务,那么您已经体验了语音识别的强大功能。

语音识别的应用范围很广,从语音数据(如语音邮件)的自动转录到通过语音与机器人进行交互。

在本教程中,您将看到我们如何开发一个非常简单的语音识别应用程序,该应用程序能够识别音频文件中的语音以及麦克风中的实时声音。所以,让我们开始吧。

已使用Python开发了几种语音识别库。但是,我们将使用SpeechRecognition库,它是所有库中最简单的。

安装SpeechRecognition库

执行以下命令以安装库: 

$ pip install SpeechRecognition

音频文件中的语音识别

在本节中,您将看到我们如何将语音从音频文件转换为文本。可以从此链接下载将用作输入的音频文件。将文件下载到本地文件系统。

与往常一样,第一步是导入所需的库。在这种情况下,我们只需要导入speech_recognition刚刚下载的库。 

import speech_recognition as speech_recog

要将语音转换为文本,我们需要的唯一一个类是模块中的Recognizerspeech_recognition。根据用于将语音转换为文本的基础API,Recognizer该类具有以下方法:

  • recognize_bing():使用Microsoft Bing Speech API
  • recognize_google():使用Google Speech API
  • recognize_google_cloud():使用Google Cloud Speech API
  • recognize_houndify():使用SoundHound的Houndify API
  • recognize_ibm():使用IBM Speech to Text API
  • recognize_sphinx():使用PocketSphinx API

在上述所有方法中,recognize_sphinx()可以离线使用该方法将语音转换为文本。

要从音频文件中识别语音,我们必须创建模块AudioFile类的对象speech_recognition。您要转换为文本的音频文件的路径传递到AudioFile该类的构造函数。执行以下脚本:

sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')

在上面的代码中,将路径更新为要转录的音频文件。

我们将使用该recognize_google()方法来转录音频文件。但是,该recognize_google()方法需要模块的AudioData对象speech_recognition作为参数。要将音频文件转换为AudioData对象,我们可以使用类的record()方法Recognizer。我们需要将AudioFile对象传递给record()方法,如下所示:

with sample_audio as audio_file:
    audio_content = recog.record(audio_file)

现在,如果您检查audio_content变量的类型,您将看到它具有type speech_recognition.AudioData

type(audio_content)

输出:

speech_recognition.AudioData

现在,我们可以简单地将audio_content对象传递给类对象的recognize_google()方法,Recognizer()音频文件将转换为文本。执行以下脚本:

recog.recognize_google(audio_content)

输出:

'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas tank degrees office 30 face before you go out the race was badly strained and hung them the stray cat gave birth to kittens the young girl gave no clear response the meal was called before the bells ring what weather is in living'

上面的输出显示了音频文件的文本。您会看到该文件尚未100%正确地转录,但是准确性是相当合理的。

设置持续时间和偏移值

除了转录完整的语音,您还可以转录音频文件的特定片段。例如,如果您只想转录音频文件的前10秒,则需要传递10作为方法duration参数的值record()。看下面的脚本:

sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
    audio_content = recog.record(audio_file, duration=10)

recog.recognize_google(audio_content)

输出:

'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas'

同样,您可以使用offset参数从头开始跳过音频文件的某些部分。例如,如果您不想转录音频的前4秒钟,则将4作为offset属性值传递。例如,以下脚本跳过音频文件的前4秒,然后将音频文件转录10秒。

sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
    audio_content = recog.record(audio_file, offset=4, duration=10)

recog.recognize_google(audio_content)

输出:

'take the winding path to reach the lake no closely the size of the gas tank web degrees office dirty face'

处理噪音

由于多种原因,音频文件可能包含噪音。噪声实际上会影响语音到文本翻译的质量。为了减少噪音,Recognizer该类包含adjust_for_ambient_noise()方法,该方法将AudioData对象作为参数。以下脚本显示了如何通过消除音频文件中的噪声来改善转录质量:

sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
    recog.adjust_for_ambient_noise(audio_file)
    audio_content = recog.record(audio_file)

recog.recognize_google(audio_content)

输出:

'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas tank web degrees office 30 face before you go out the race was badly strained and hung them the stray cat gave birth to kittens the younger again no clear response the mail was called before the bells ring what weather is in living'

输出结果与我们之前获得的结果非常相似。这是由于音频文件中的噪音已经很小。

现场麦克风的语音识别

在本部分中,您将看到如何转录通过系统上的麦克风接收的实时音频。

有多种方法可以处理通过麦克风接收的音频输入,并且已经开发了各种库来处理。这样的库之一就是PyAudio。执行以下脚本来安装该PyAudio库: 

$ pip install PyAudio

现在,要转录的音频源是麦克风。要从麦克风捕获音频,我们需要首先创建模块Microphone类的对象Speach_Recogniton,如下所示: 

mic = speech_recog.Microphone()

要查看系统中所有麦克风的列表,可以使用以下list_microphone_names()方法: 

speech_recog.Microphone.list_microphone_names()

输出: 

['Microsoft Sound Mapper - Input',
 'Microphone (Realtek High Defini',
 'Microsoft Sound Mapper - Output',
 'Speakers (Realtek High Definiti',
 'Microphone Array (Realtek HD Audio Mic input)',
 'Speakers (Realtek HD Audio output)',
 'Stereo Mix (Realtek HD Audio Stereo input)']

这是我的系统中可用的麦克风列表。请记住,您的列表看起来可能会有所不同。

下一步是从麦克风捕获音频。为此,您需要调用该类的listen()方法Recognizer()。与record()方法一样,该listen()方法也返回speech_recognition.AudioData对象,然后可以将该对象传递给该recognize_google()方法。

以下脚本提示用户在麦克风中说些什么,然后打印用户说的内容: 

with mic as audio_file:
    print("Speak Please")

    recog.adjust_for_ambient_noise(audio_file)
    audio = recog.listen(audio_file)

    print("Converting Speech to Text...")
    print("You said: " + recog.recognize_google(audio))

一旦执行了上面的脚本,您将看到以下消息: 

Please say something

此时,说出您想说的话,然后停下来。暂停后,您会看到说话的内容。这是我得到的输出: 

Converting Speech to Text...
You said: hello this is normally from stack abuse abuse this is an article on speech recognition I hope you will like it and this is just a test speech and when I will stop speaking are you in today thank you for Reading

值得一提的是,如果recognize_google()方法无法将您说的单词与存储库中的任何单词匹配,则会引发异常。您可以通过说一些难以理解的词来进行测试。您应该看到以下异常: 

Speak Please
Converting Speech to Text...
---------------------------------------------------------------------------
UnknownValueError                         Traceback (most recent call last)
 in 
      8     print("Converting Speech to Text...")
      9
---> 10     print("You said: " + recog.recognize_google(audio))
     11
     12

~\Anaconda3\lib\site-packages\speech_recognition\__init__.py in recognize_google(self, audio_data, key, language, show_all)
    856         # return results
    857         if show_all: return actual_result
--> 858         if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
    859
    860         if "confidence" in actual_result["alternative"]:

UnknownValueError

更好的方法是在调用方法try时使用该块recognize_google(),如下所示: 

with mic as audio_file:
    print("Speak Please")

    recog.adjust_for_ambient_noise(audio_file)
    audio = recog.listen(audio_file)

    print("Converting Speech to Text...")

    try:
        print("You said: " + recog.recognize_google(audio))
    except Exception as e:
        print("Error: " + str(e))

结论

语音识别在人机交互和自动语音转录领域具有各种有用的应用。本文简要说明了通过speech_recognition库在Python中进行语音转录的过程,并说明了当音频源是音频文件或现场麦克风时如何将语音转换为文本。