85 lines
2.1 KiB
PHP
85 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace app;
|
|
|
|
use Workerman\Connection\TcpConnection;
|
|
use IFlytek\Xfyun\Speech\ChatClient;
|
|
use WebSocket\Client;
|
|
use Workerman\Connection\AsyncTcpConnection;
|
|
use support\Request;
|
|
use Webman\Container;
|
|
|
|
use function DI\env;
|
|
|
|
class Tts
|
|
{
|
|
private $app_id = '2eda6c2e';
|
|
|
|
private $api_key = '12ec1f9d113932575fc4b114a2f60ffd';
|
|
|
|
private $api_secret = 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2';
|
|
|
|
|
|
private $ttsConfig = [
|
|
'aue' => 'lame',
|
|
'sfl' => 1,
|
|
'vcn' => 'x4_lingxiaoyao_en'
|
|
];
|
|
|
|
public function onConnect(TcpConnection $connection)
|
|
{
|
|
echo "onConnect\n";
|
|
}
|
|
|
|
public function onWebSocketConnect(TcpConnection $connection, $http_buffer)
|
|
{
|
|
echo "onWebSocketConnect\n";
|
|
}
|
|
|
|
public function onMessage(TcpConnection $connection, $data)
|
|
{
|
|
|
|
$data = json_decode($data);
|
|
if (isset($data->data)) {
|
|
$data = $data->data;
|
|
}
|
|
|
|
if ($data == '') {
|
|
return $connection->send(['header' => ['code' => 10003, 'message' => '消息不能为空']]);
|
|
}
|
|
|
|
if ($data != '') {
|
|
$arr=explode('。',$data);
|
|
foreach($arr as $k=>$v){
|
|
if(strlen($v)>1){
|
|
$url = $this->tts($v);
|
|
$resp['mp3'] = $url;
|
|
$resp['key'] = 'true';
|
|
$response = json_encode($resp, true);
|
|
$connection->send($response);
|
|
}
|
|
}
|
|
$resp['mp3'] = '';
|
|
$resp['key'] = 'false';
|
|
$response = json_encode($resp, true);
|
|
$connection->send($response);
|
|
|
|
|
|
}
|
|
}
|
|
|
|
public function onClose(TcpConnection $connection)
|
|
{
|
|
echo "onClose\n";
|
|
}
|
|
|
|
function tts($text)
|
|
{
|
|
|
|
$name = time() . rand(1, 100000) . '.mp3';
|
|
$tts = new extend\IFlytek\Xfyun\Speech\TtsClient($this->app_id, $this->api_key, $this->api_secret, $this->ttsConfig);
|
|
file_put_contents(public_path('tts') . '/' . $name, $tts->request($text)->getBody()->getContents());
|
|
return 'https://chat.lihaink.cn/tts/' . $name;
|
|
}
|
|
}
|