使用AsyncTcpConnection 作為websocket客戶端,發(fā)送音頻流數(shù)據(jù)。
// 創(chuàng)建異步TCP連接
$connection = new AsyncTcpConnection($this->url);
// $connection->maxSendBufferSize = 1048576 * 20;
$connection->transport = 'ssl';
// 當(dāng)連接建立時(shí)發(fā)送數(shù)據(jù)
$connection->onWebSocketConnect = function (AsyncTcpConnection $connect, $response) {
Log::info('騰訊實(shí)時(shí)asr Connected to Tencent AI Recognition' . $response);
};
// 當(dāng)接收到數(shù)據(jù)時(shí)
$connection->onMessage = function (AsyncTcpConnection $connect, $message) {
static $ok = true;
Log::info($message);
if ($ok) {
$ok = false;
$audioFilePath = "/home/www/webman/public/test.pcm"; // 請(qǐng)?zhí)鎿Q為您的音頻文件路徑
$audioData = file_get_contents($audioFilePath);
// 分片大小,根據(jù)騰訊云文檔設(shè)置
$chunkSize = 1280; // 舉例,具體大小請(qǐng)參照騰訊云文檔
$totalSize = strlen($audioData);
Log::info('發(fā)送音頻數(shù)據(jù):' . $totalSize);
// 分片發(fā)送
for ($i = 0; $i < $totalSize; $i += $chunkSize) {
$chunkData = substr($audioData, $i, $chunkSize);
// Log::info('', ['len' => strlen($chunkData)]);
// 發(fā)送分片
$flag = $connect->send($chunkData, true);
Log::info('', ['flag' => $flag]);
usleep(40 * 1000);
}
// 發(fā)送結(jié)束標(biāo)志
// $connection->send('{"end": true}');
Log::info('發(fā)送結(jié)束數(shù)據(jù)');
$connect->send('{"type":"end"}');
}
};
send buffer full and drop package
發(fā)送緩沖區(qū)滿了,參見文檔
http://wtbis.cn/doc/workerman/worker/on-buffer-full.html
另外workerman文檔開發(fā)者必讀里有說,workerman里不能用sleep語句。要延遲發(fā)送用定時(shí)。