使用Python开始语音识别

26

我想了解如何开始进行语音识别。不使用任何相对“黑匣子”的库,而是要知道如何编写一个简单的语音识别脚本。我已经做了一些搜索,发现并没有太多相关信息。但我看到有关于“声音”或音节的字典,可以组合成文本。所以我的问题基本上就是:在哪里可以开始进行这方面的学习呢?

此外,考虑到这可能有些理想化,我也可以先使用某个库来实现语音识别。我发现一些语音转文字的库和API只输出一个结果。这样做也没关系,但不够可靠。因为我当前的程序会检查输入的任何文本的语法和其他方面,所以如果我得到了10个顶部结果,那么它可以逐个检查并排除任何不合理的结果。

9个回答

7

我知道这个问题很老,但是为了方便未来的人:

我使用 speech_recognition 模块,我非常喜欢它。唯一的问题是,它需要互联网,因为它使用 Google 识别语音。但在大多数情况下,这不应该是一个问题。识别几乎完美。

编辑:

speech_recognition 包不仅可以使用 Google 进行翻译,还可以使用其他工具,例如 CMUsphinx(允许离线识别)。唯一的区别是在 recognize 命令中进行微小的更改:

https://pypi.python.org/pypi/SpeechRecognition/

这里有一个小的代码示例:

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as source:                # use the default microphone as the audio source
    audio = r.listen(source)                   # listen for the first phrase and extract it into audio data

try:
    print("You said " + r.recognize_google(audio))    # recognize speech using Google Speech Recognition - ONLINE
    print("You said " + r.recognize_sphinx(audio))    # recognize speech using CMUsphinx Speech Recognition - OFFLINE
except LookupError:                            # speech is unintelligible
    print("Could not understand audio")

有一件事对我来说不太好用:无限循环中的听取。几分钟后,它会卡住(它没有崩溃,只是没有响应)。

编辑: 如果您想在没有无限循环的情况下使用麦克风,您应该指定录制长度。 示例代码:

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Speak:")
    audio = r.listen(source, None, "time_to_record")  # recording

2
这似乎对我不起作用。我一直在说话并等待它输出结果。但是什么也没有! - yogk
2
嗯,尝试让它在一个无限循环中监听。(将Try-Except块转换为while 1循环。) - Noah Krasser
1
类型错误:该函数需要2个参数(提供了3个参数) 在行audio = r.listen(source)上出现了这个错误。 - Aquib

7

更新:这个方法已经失效了

因为谷歌关闭了它的平台

--

你可以使用https://pypi.python.org/pypi/pygsr

$> pip install pygsr

使用示例:

from pygsr import Pygsr
speech = Pygsr()
# duration in seconds
speech.record(3)
# select the language
phrase, complete_response = speech.speech_to_text('en_US')

print phrase

我在安装了以上链接中给出的软件包后尝试了它,但是它报错了。root@ubuntu:/home/mp/n# python pygsr.py Traceback (most recent call last): File "pygsr.py", line 1, in <module> from pygsr import Pygsr File "/home/mp/n/pygsr.py", line 1, in <module> from pygsr import Pygsr ImportError: 无法导入名称Pygsr - pkm
现在谷歌的URL http://www.google.com/speech-api/v1/recognize?lang=%s 已经失效,返回404错误响应。 - Dineshkumar
4
-1 是因为它只是对谷歌“黑盒子”的包装,而不是一个可以玩耍以了解语音识别工作原理的工具包。 - anatoly techtonik

7

Pocketsphinx也是一个不错的选择。通过SWIG提供的Python绑定,使其很容易集成到脚本中。

例如:

from os import environ, path
from itertools import izip

from pocketsphinx import *
from sphinxbase import *

MODELDIR = "../../../model"
DATADIR = "../../../test/data"

# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', path.join(MODELDIR, 'hmm/en_US/hub4wsj_sc_8k'))
config.set_string('-lm', path.join(MODELDIR, 'lm/en_US/hub4.5000.DMP'))
config.set_string('-dict', path.join(MODELDIR, 'lm/en_US/hub4.5000.dic'))
decoder = Decoder(config)

# Decode static file.
decoder.decode_raw(open(path.join(DATADIR, 'goforward.raw'), 'rb'))

# Retrieve hypothesis.
hypothesis = decoder.hyp()
print 'Best hypothesis: ', hypothesis.best_score, hypothesis.hypstr

print 'Best hypothesis segments: ', [seg.word for seg in decoder.seg()]

# Access N best decodings.
print 'Best 10 hypothesis: '
for best, i in izip(decoder.nbest(), range(10)):
    print best.hyp().best_score, best.hyp().hypstr

# Decode streaming data.
decoder = Decoder(config)
decoder.start_utt('goforward')
stream = open(path.join(DATADIR, 'goforward.raw'), 'rb')
while True:
    buf = stream.read(1024)
    if buf:
        decoder.process_raw(buf, False, False)
    else:
        break
decoder.end_utt()
print 'Stream decoding result:', decoder.hyp().hypstr

文件“source_file.py”,第40行 break 语法错误:循环外的'break' - voices
可能是缩进问题,已经修复了 while 循环。 - toine
1
虽然很感谢你提供的代码;但我需要先仔细研究一下。那么,所有这些音频都会被发送到Google服务器进行处理吗? - voices
不,不是这个。它使用了开源软件pocketsphinx。您应该查看他们的网站:https://github.com/cmusphinx/pocketsphinx或者cmusphinx.sourceforge.net/。 - toine

7
如果你真的想从基础开始理解语音识别,可以寻找一个好的Python信号处理包,然后独立地了解语音识别,而不是依赖于软件。但是,语音识别是一个极其复杂的问题(基本上是因为我们说话时声音以各种方式相互作用)。即使你使用最好的语音识别库,也不会发现自己没有更多的事情可做。

6

但这与语音识别本身无关。该幻灯片包含一般的音频处理 - 与识别无关。 - Kevin Martin Jose
@lonesword 这个问题是关于入门的,信号处理是了解语音和声音处理的先决条件。 - anatoly techtonik

4

Dragonfly提供了一个在Windows上进行语音识别的干净框架。查看他们的文档以获取使用示例。如果您不需要Dragonfly提供的大规模功能,则可以考虑查看不再维护的PySpeech库。

他们的源代码看起来很容易理解,也许这是您首先想要查看的内容。


我目前使用的是64位Windows,所以无法让它们两个都工作,不过还是谢谢。 - bs7280

0
import speech_recognition as SRG 
import time
store = SRG.Recognizer()
with SRG.Microphone() as s:
     
    print("Speak...")
     
    audio_input = store.record(s, duration=7)
    print("Recording time:",time.strftime("%I:%M:%S"))
    
    try:
        text_output = store.recognize_google(audio_input)
        print("Text converted from audio:\n")
        print(text_output)
        print("Finished!!")
 
        print("Execution time:",time.strftime("%I:%M:%S"))
    except:
           print("Couldn't process the audio input.")

这应该可以工作。你将从默认麦克风获得音频输入,并保存到 text_output 变量中的文本形式。 您可以查看此链接以获取更多信息:https://www.journaldev.com/37873/python-speech-to-text-speechrecognition

我们基本上是先从麦克风录制音频,然后将其用作语音识别器的输入。 唯一需要注意的是,您需要有活动的互联网连接和这两个必需的Python库speech_recognitionpyaudio


0

以下是使用在线库在Python中开始使用语音识别的简单方法:

SpeechRecognition 

Google API:

recognize_google()

要求:

1-Python 3.9
2-Anaconda (Launch Jupyter)

在代码中

步骤1:

pip install pyaudio
pip install speechrecognition

步骤2:-

import speech_recognition as sr
r = sr.Recognizer()

第三步:- 使用默认麦克风作为音频源

with sr.Microphone() as source:                
    r.adjust_for_ambient_noise(source, duration = 5)
    audio = r.listen(source)

步骤4:

print("Speak Anything :")
try:
        text = r.recognize_google(audio)
        
        print("You said : {}".format(text))
    
except:
           print("Sorry could not recognize what you said")

步骤5:

当上述代码运行正常,但响应速度较慢或有时为空白时, 可以添加几行代码:

r.pause_threshold = 1

完整代码

pip install pyaudio
pip install speechrecognition


*Here is the code*

    import speech_recognition as sr
    
    def recog():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say Something")
            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
    
        try:
            print("Recognizing..")
            text = r.recognize_google(audio, language='en-in') # Specify Language Code
            print("You said {}".format(text))
    
        except Exception as e:
            print(e)
            print("Sorry")
    
    recog()

0
这可能是学习的最重要事情:信号处理的基本概念,尤其是数字信号处理(DSP)。对抽象概念的一些理解将为您准备好scipy.signal中琳琅满目的工具。
首先是模拟到数字转换(ADC)。这实际上属于音频工程领域,现在已经成为录制过程的一部分,即使您只是将麦克风连接到计算机。
如果您从模拟录音开始,可能需要将旧磁带或黑胶唱片转换为数字形式,或者从旧录像带中提取音频。最简单的方法是将源播放到计算机的音频输入接口,并使用内置硬件和软件将原始线性脉冲编码调制(LPCM)数字信号捕获到文件中。Audacity是一个非常适合此类操作的工具,而且还有更多功能。
傅里叶变换是您的朋友。在数据科学中,它非常适用于特征提取和特征空间维度缩减,尤其是当您正在寻找涵盖整个样本音频变化的特征时。在此处无法解释所有细节,但时间域中的原始数据对于机器学习算法来说比频率域中的原始数据更难处理。
您将特别使用快速傅里叶变换(FFT),这是离散傅里叶变换(DFT)的一种非常高效的形式。现在通常在DSP硬件中执行FFT。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接