+
91
-

小程序如何实现websocket语音实时通话?

小程序如何实现websocket语音实时通话?


网友回复

+
15
-

我们以微信小程序为例

后端采用swoole搭建websocket服务

<?php

$server = new Swoole\WebSocket\Server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
$server->set([
    'daemonize' => false,
    'ssl_cert_file' => "/data/cert/6284283_web.debug.only.bfw.wiki.pem",
    'ssl_key_file'  => "/data/cert/6284283_web.debug.only.bfw.wiki.key",
]);
$server->on('open', function($server, $req) {
    echo "connection open: {$req->fd}\n";
});

$server->on('message', function($server, $frame) {
   echo "received message\n";
    // 确保我们处理的是二进制数据
    //if ($frame->opcode == WEBSOCKET_OPCODE_BINARY) {
        // 广播音频数据到所有其他连接的客户端
      //  foreach($server->connections as $fd) {
          //  if($fd != $frame->fd) {
             //   $server->push($fd, $frame->data, WEBSOCKET_OPCODE_BINARY);
           // }
       // }
   // }
    $server->push($frame->fd, $frame->data,WEBSOCKET_OPCODE_BINARY);
});

$server->on('close', function($server, $fd) {
    echo "connection close: {$fd}\n";
});

$server->start();

小程序采用getRecorderManager与createInnerAudioContext实现实时录制与播放对方的声音,完整的微信小程序代码如下:

wxml

<view class="container" style="padding-top: 20vh;">
  <button bindtap="startCall" disabled="{{isCallStarted}}">开始通话</button>
  <button bindtap="stopCall" disabled="{{!isCallStarted}}">结束通话</button>
</view>

点击查看剩余代码

我知道答案,我要回答