• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于python:检测英语口语使用百度云语音识别

python 搞代码 3年前 (2022-02-20) 11次浏览 已收录 0个评论
文章目录[隐藏]

我的项目需要

  1. 在命令行窗口运行;
  2. 程序运行时,会让你输出一句英语,而后你须要对着麦克风读出这句英语;
  3. 程序会判断你读的对不对,如果不对会让你重读,直到读对为止;
  4. 应用百度云语音辨认:https://ai.baidu.com/tech/spe…

Python编程知识点

  • while循环
  • 用户输出字符串
  • 字符串小写
  • 条件判断
  • 自定义函数
  • 异样解决
  • SpeechRecognition 模块 (装置: pip install SpeechRecognition)
  • pyaudio 模块 (装置: pip install pyaudio)
  • baidu-aip 模块(装置: pip install baidu-aip)

参考代码

import speech_recognition as sr
from aip import AipSpeech

# 请本人注册百度云语音辨认:https://ai.baidu.com/tech/speech/asr
VOICE_APP_ID = 'YOUR_ASR_APP_ID'
VOICE_API_KEY = 'YOUR_ASR_APP_KEY'
VOICE_SECRET_KEY = 'YOUR_ASR_SECRET_KEY'
voice_client = AipSpeech(VOICE_APP_ID, VOICE_API_KEY, VOICE_SECRET_KEY)


# 百度云语音辨认
def asr(audio_data):
    wav_data = audio_data.get_wav_data(
        convert_rate=16000,
        convert_width=2
    )
    res = voice_client.asr(wav_data, 'wav', 16000, {
        'dev_pid': 1737,
    })
    if res['err_no'] == 0:
        return ''.join(res['result'])
    else:
        return ''


def recognize_speech_from_mic(recognizer, microphone):
    '''
    麦克风录音并转文字 `microphone`.
    :param recognizer: 语音识别器
    :param microphone: 麦克风
    :return: `None` 如果辨认失败返回None,否则返回语音文字
    '''
    print('开始朗诵')
    # 录音并去除乐音
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)

    # 应用百度云语音辨认
    try:
        text = asr(audio)
    except Exception as e:
        print(e)
        text = None

    return text


if __name__ == '__main__':
    # 输出
    text = input('请输出一句英语: ').strip()

    # 创立语音识别器和麦克风
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()

    # 录音并获取文字
    speech_text = recognize_speech_from_mic(recognizer, microphone)

    while speech_text != None and text.lower() != speech_text.lower():
        print('{} ×'.format(speech_text))
        speech_text = recognize_speech_from_mic(recognizer, microphone)

    if speech_text:
        print('{} {}'.format(speech_text, '✓'))
    else:
        print('语音辨认服务暂不可用,请稍后再试。')

运行测试

  • 应用 pip install requirements.txt 装置模块: pyaudioSpeechRecognitionbaidu-aip
  • 运行
<code class="shell">python 5.py

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:检测英语口语使用百度云语音识别
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址