python 腾讯语音转文字简单示列代码

import base64
import json
import time

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models


def send_task(path):
    try:
        cred = credential.Credential("SecretId", "SecretKey")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = asr_client.AsrClient(cred, "", clientProfile)

        req = models.CreateRecTaskRequest()
        fwave = open(path, mode='rb').read()

        dataLen = len(fwave)

        base64Wav = base64.b64encode(fwave).decode('utf8')
        params = {
            "EngineModelType": "8k_en",
            "ChannelNum": 1,
            "ResTextFormat": 0,
            "SourceType": 1,
            "Data": base64Wav, "DataLen": dataLen
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreateRecTask(req)

        print(resp.to_json_string())
        return json.loads(resp.to_json_string())


    except TencentCloudSDKException as err:
        print(err)


def get_task(t_id):
    try:
        cred = credential.Credential("SecretId", "SecretKey")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = asr_client.AsrClient(cred, "", clientProfile)

        req = models.DescribeTaskStatusRequest()
        params = {
            "TaskId": int(t_id)
        }
        req.from_json_string(json.dumps(params))

        resp = client.DescribeTaskStatus(req)
        print(resp.to_json_string())
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        print(err)


def get_mp3_res_tengxun(path):
    data = send_task(path)
    for i in range(1, 15):
        d = get_task(data.get('Data').get('TaskId'))
        if d:
            d = json.loads(d)
            if d.get('Data').get('StatusStr') == 'success':
                return d.get('Data').get('Result').split(']  ')[-1].replace('\n', '')
            time.sleep(2)
    return None



改成自己的 信息就行

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值