首先新建AipSpeech(百度语音识别的SDK客户端)

""" 百度AI开放平台的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

然后定义一个语音转文字的函数

path = 'voices/voice.wav' #需要提前创建voices文件夹

# 调用百度语音转文字接口,将语音转文本
def listen():
    with open(path, 'rb') as fp:
        voice = fp.read()

    result = client.asr(voice, 'wav', 16000, {'dev_pid': 1537})
    try:
        result_text = result["result"][0]
        print(result_text)
    except KeyError:
        print("KeyError")
        print(result)

定义录音的函数

#使用speech_recognition录音
def record_audio(rate=16000):
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=rate) as source:
        print("please say something")
        r.adjust_for_ambient_noise(source) #动态调整能量阈值以解决环境噪声(自动调整静音检测的阈值)(使用后可显著提高效果)
        audio = r.listen(source,phrase_time_limit=59) #限制录音的最长时长为59秒,防止超出百度的时间限制
        print('record finish')
 
    with open("voices/voice.wav", "wb") as f:
        f.write(audio.get_wav_data())

Microphone()的使用方法
在这里插入图片描述


实例化Recognize()后调用下面的方法(这里面的r指的就是下面的recognizer_instence)
在这里插入图片描述


用speech_recognition模块可以实现有静音识别的录音(还可以与snowboy集成,实现热词识别)

speech_recognition listen函数的用法


动态调整能量阈值以解决环境噪声(自动调整静音检测的阈值)(使用后可显著提高效果)
在这里插入图片描述
参考手册:https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst


完整代码:

import speech_recognition as sr
from aip import AipSpeech

APP_ID = '18490357'
API_KEY = 'PdZpve6uqC7qg8kgW7LsazWZ'
SECRET_KEY = '4fNWQFkTeyxAku412byYYoRArBDGkiSg'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
path = 'voices/voice.wav' ##需要提前创建voices文件夹

#使用speech_recognition录音
def record_audio(rate=16000):
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=rate) as source:
        print("please say something")
        r.adjust_for_ambient_noise(source) #动态调整能量阈值以解决环境噪声(自动调整静音检测的阈值)(使用后可显著提高效果)
        audio = r.listen(source,phrase_time_limit=59)#限制录音的最长时长为59秒,防止超出百度的时间限制
        print('record finish')
 
    with open("voices/voice.wav", "wb") as f:
        f.write(audio.get_wav_data())
 
# 调用百度语音转文字接口,将语音转文本
def listen():
    with open(path, 'rb') as fp:
        voice = fp.read()

    result = client.asr(voice, 'wav', 16000, {'dev_pid': 1537})
    try:
        result_text = result["result"][0]
        print(result_text)
    except KeyError:
        print("KeyError")
        print(result)

if __name__ == "__main__":
    while True:
        record_audio()
        listen()
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐