使用腾讯C++ SDK接口调用API进行语音识别

最近在收集哆啦A梦的视频资源,同时在收集藤子F不二雄老师的异色短篇集视频,其中有一集是长达48分钟的无字幕视频(还是从油管上偷来的)。

去学日语是不可能的,这辈子都不可能的,搜索语音识别时发现腾讯有提供免费的语音识别服务,只需要按照其提供的接口就可以了(当然了,不可能不限时不限量)。

本人只会C++,所以使用其C++接口。

先下载CPP接口代码

1
2
3
4
5
6
7
git clone https://github.com/tencentcloud/tencentcloud-sdk-cpp
cd tencentcloud-sdk-cpp
mkdir build
cd build
cmake ..
make -j12
sudo make install

将需要识别的音频文件上传到能够通过公网访问的地方,我是上传到本服务器上就可以了。

然后按照官网的录音文件识别请求录音文件识别结果查询进行编写代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/core/profile/ClientProfile.h>
#include <tencentcloud/core/profile/HttpProfile.h>
#include <tencentcloud/asr/v20190614/AsrClient.h>
#include <tencentcloud/asr/v20190614/model/CreateRecTaskRequest.h>
#include <tencentcloud/asr/v20190614/model/CreateRecTaskResponse.h>
#include <iostream>
#include <string>
#include <vector>

using namespace TencentCloud;
using namespace TencentCloud::Asr::V20190614;
using namespace TencentCloud::Asr::V20190614::Model;
using namespace std;

int main() {
Credential cred = Credential("publicid", "secretid");

HttpProfile httpProfile = HttpProfile();
httpProfile.SetEndpoint("asr.tencentcloudapi.com");

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

CreateRecTaskRequest req = CreateRecTaskRequest();

req.SetEngineModelType("16k_ja");
req.SetChannelNum(1);
req.SetSpeakerDiarization(0);
req.SetSpeakerNumber(0);
req.SetResTextFormat(0);
req.SetSourceType(0);
req.SetUrl("https://feater.top/path/to/file.mp3");

auto outcome = client.CreateRecTask(req);
if (!outcome.IsSuccess())
{
cout << outcome.GetError().PrintAll() << endl;
return -1;
}
CreateRecTaskResponse resp = outcome.GetResult();
uint64_t taskId=resp.GetData().GetTaskId();

//retirve result
DescribeTaskStatusRequest req2 = DescribeTaskStatusRequest();

req2.SetTaskId(taskId);

auto outcome2 = client.DescribeTaskStatus(req2);
if (!outcome2.IsSuccess())
{
cout << outcome2.GetError().PrintAll() << endl;
return -1;
}
DescribeTaskStatusResponse resp2 = outcome2.GetResult();
std::cout<<resp2.GetData().GetStatus();

return 0;
}

同时链接刚刚编译好的库:

1
2
LIBS += -L/usr/local/lib -ltencentcloud-sdk-cpp-core -ltencentcloud-sdk-cpp-api \
-ltencentcloud-sdk-cpp-asr

需要记录下taskId,官网API说最多一秒查询50次。如果resp2.GetData().GetStatus();结果为2就表示识别成功。

可以通过:

1
2
3
4
int status = resp.GetData().GetStatus();
if(status==2){
std::cout<<resp.GetData().GetResult();
}

获取结果

result