调用腾讯云语音转文本

306 阅读1分钟

一、申请SecretId和SecretKey

1、点击账户信息 在这里插入图片描述

2、选择访问管理 在这里插入图片描述

3、点击访问密钥--API密钥管理 在这里插入图片描述

4、点击新建密钥 在这里插入图片描述在这里插入图片描述 生成密钥成功

二、调用代码

安装包

pip install --upgrade tencentcloud-sdk-python
# -*- coding: utf8 -*-

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

SecretId = ''
SecretKey = ''

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_zh",
            "ChannelNum": 2,
            "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)



if __name__ == '__main__':
    path = "data/record/20220715085756.mp3"
    result_tx = send_task(path)
    d = get_task(result_tx.get('Data').get('TaskId'))
    d = json.loads(d)
    result_text = d.get('Data').get('Result')