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

40次阅读

共计 1620 个字符,预计需要花费 5 分钟才能阅读完成。

我的项目需要

  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
  • 运行
python 5.py

正文完
 0