python实现语音转文字(百度接口)

import json
import base64
import os
import requests


RATE = "16000"
FORMAT = "wav"
CUID="wate_play"
DEV_PID="1536"

def get_token():
    server = "https://openapi.baidu.com/oauth/2.0/token?"
    grant_type = "client_credentials"
    #API Key
    client_id = "vyYLov63W6x33nIPvwVdLLsX"
    #Secret Key
    client_secret = "EzgQoFF9xp62SeGCXCBaD8FjWNxvl9kZ"

    #拼url
    url ="%sgrant_type=%s&client_id=%s&client_secret=%s"%(server,grant_type,client_id,client_secret)
    #获取token
    res = requests.post(url)
    token = json.loads(res.text)["access_token"]

    return token

def get_word(token):
    wavPath = './static/yuyin/record.wav'
    with open(wavPath, "rb") as f:
        speech = base64.b64encode(f.read()).decode('utf8')
    size = os.path.getsize(wavPath)
    headers = { 'Content-Type' : 'application/json'}
    url = "https://vop.baidu.com/server_api"
    data={
            "format":FORMAT,
            "rate":RATE,
            "dev_pid":DEV_PID,
            "speech":speech,
            "cuid":CUID,
            "len":size,
            "channel":1,
            "token":token,
        }
    try:
        req = requests.post(url,json.dumps(data),headers)
        result = json.loads(req.text)
        ret=result["result"][0]
    except :
        ret = None
    return ret[:-1]

wavPath 为wav文件路径

Secret key 和Api key为百度接口获取的参数

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值