我想通过websocket 连接将二进制音频数据发送到 IBM watson STT 服务。我已成功建立连接,现在尝试以以下格式发送数据:
{
"action":"start",
"content-type": "audio/l16;rate=44100"
}
<binary audio data>
{
"action":"stop"
}
为此:我正在读取一个原始音频文件(extn .pcm),如下所示
#include <string>
#include <fstream>
ifstream fin;
string binarydata, bdataline;
fin.open("/home/rohan/TestFile.pcm", ios::binary | ios::in);
while (fin) {
// Read a Line from File
getline(fin, bdataline);
binarydata = binarydata + bdataline;
}
问题 1:我不确定我是否正确读取了二进制数据。应该是数据类型binarydata
吗string
?
接下来在boost websocket上发送数据(握手后)我遵循了这个例程
void on_handshake(beast::error_code ec)
{
if(ec)
return fail(ec, "handshake");
// Send the Start message
ws_.async_write(net::buffer("{\"action\":\"start\",\"content-type\": \"audio/l16;rate=44100\"}"), bind(&session::on_start, shared_from_this(), placeholders::_1));
}
void on_start(beast::error_code ec)
{
if(ec)
return fail(ec, "write:start");
ws_.async_write(net::buffer(binarydata), bind(&session::on_binarysent, shared_from_this(), placeholders::_1));
}
void on_binarysent(beast::error_code ec)
{
if(ec)
return fail(ec, "write:Msg");
ws_.async_write(net::buffer("{\"action\":\"stop\"}"), bind(&session::on_write, shared_from_this(), placeholders::_1));
}
void on_write( beast::error_code ec) //,
{
if(ec)
return fail(ec, "write:end");
ws_.async_read(buffer_, bind(&session::on_start, shared_from_this(), placeholders::_1));
}
该程序不显示任何输出并退出
write:start:WebSocket 流在两个端点都正常关闭
问题 2:数据是否按预期正确运行?如何检查?(预计:见此链接)
websocket如何在不发送关闭命令的情况下关闭?
更新:
void on_start(beast::error_code ec)
{
if(ec)
return fail(ec, "write:start");
ifstream infile("/home/rohan/TestFile.pcm", ios::in | ios::binary);
streampos FileSize;
if (infile) {
// Get the size of the file
infile.seekg(0, ios::end);
FileSize = infile.tellg();
infile.seekg(0, ios::beg);
}
char binarydata[(size_t)FileSize];
ws_.binary(true);
// Send binary data
ws_.async_write(net::buffer(binarydata, sizeof(binarydata)), bind(&session::on_binarysent, shared_from_this(), placeholders::_1));
}