Python 实现语音转文本

Python 实现语音转文本

Python可以使用多种方式来实现语音转文本,下面介绍其中两种。

方法一:使用Google Speech API

Google Speech API 是 Google 在 2012 年推出的一个 API,可以用于实现语音转文本。使用 Google Speech API 需要安装 SpeechRecognition 库,可以使用 pip 安装:

pip install SpeechRecognition

安装完成后,可以使用下面的代码实现语音转文本:

import speech_recognition as sr

# 设置音频文件的位置
audio_file = './audio.wav'

# 创建 SpeechRecognition 对象
r = sr.Recognizer()

# 读取音频文件
with sr.AudioFile(audio_file) as source:
    audio = r.record(source)

# 识别音频文件
try:
    print(r.recognize_google(audio, language='zh-CN'))
except sr.UnknownValueError:
    raise 'Google Speech Recognition could not understand audio'
except sr.RequestError as e:
    raise 'Could not request results from Google Speech Recognition Service'

方法二:使用百度语音识别

除了 Google Speech API 外,还可以使用百度语音识别来实现语音转文本。使用百度语音识别需要安装 Baidu-Aip 库,可以使用 pip 安装:

pip install Baidu-Aip

安装完成后,可以使用下面的代码实现语音转文本:

from aip import AipSpeech

# 设置 APPID、API Key 和 Secret Key
APP_ID = 'your_app_id'
API_KEY = 'your_api_key'
SECRET_KEY = 'your_secret_key'

# 初始化 AipSpeech 对象
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 设置音频文件的位置
audio_file = './audio.wav'

# 读取音频文件
with open(audio_file, 'rb') as fp:
    audio_data = fp.read()

# 识别音频文件
res = client.asr(audio_data, 'wav', 16000, {
    'dev_pid': 1536,
})
if res['err_no'] == 0:
    print(res['result'][0])

以上就是使用 Python 实现语音转文本的两种方法。

  • 20
    点赞
  • 167
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值