托卡箱一对一视频通话

时间:2017-05-05 05:49:43

标签: javascript php api opentok tokbox

我正在开发Tokbox视频通话流程。现在我正在使用正常工作的Tokbox示例工具包,但它向我显示所有活动的用户视频。

但是我需要一个用户可以向另一个用户进行视频通话。

我的意思是我需要一对一的视频通话流程。在Tokbox中是否可能。所以请帮助解决它。

这是我的代码

use Slim\Slim;
use Gregwar\Cache\Cache;
use OpenTok\OpenTok;

if(!empty($userid))
{
$autoloader = __DIR__.'/../../../component/tokbox/vendor/autoload.php'; 
if (!file_exists($autoloader)) {
  die('You must run `composer install` in the sample app directory');
}

require($autoloader);



// PHP CLI webserver compatibility, serving static files
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
    return false;
}


// Initialize Slim application
$app = new Slim(array(
    'templates.path' => __DIR__
));

// Intialize a cache, store it in the app container
$app->container->singleton('cache', function() {
    return new Cache;
});

// Initialize OpenTok instance, store it in the app contianer
$app->container->singleton('opentok', function () {
    return new OpenTok('***', '****');
});
// Store the API Key in the app container
$app->apiKey = '45833942';
$id=$this->uri->segment('3');
$urlname=$this->uri->segment('4');
// Configure routes
$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) {

    // If a sessionId has already been created, retrieve it from the cache
    $sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
        // If the sessionId hasn't been created, create it now and store it
        $session = $app->opentok->createSession();
        return $session->getSessionId();
    });

    // Generate a fresh token for this client
    $token = $app->opentok->generateToken($sessionId);

/*$this->db->select('activemember');
$this->db->from('pshy_videocat');
$psychics=$this->db->get();
$totaluseractive= $psychics->row();
$totalactivevideouser=$totaluseractive->activemember;*/


   ?>

 <input type="hidden" id="connectionCountField" value="0"></input>
 <!--button onclick="myFunction()">Toggle Video</button-->
 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
 <script src="https://static.opentok.com/v2/js/opentok.js" charset="utf-8"></script>

 <script charset="utf-8">
 var publisher;
 var connectionCount = 0;

 var apiKey = '<?php echo '45833942'; ?>';
 var sessionId = '<?php echo $sessionId; ?>';
 var token = '<?php echo $token; ?>';

 var subscribeoptions = {width: 664, height: 421, insertMode: 'append'}

 var session = OT.initSession(apiKey, sessionId)
 .on('streamCreated', function(event) {
 session.subscribe(event.stream,'myPublisherDiv', subscribeoptions);
 })
 .connect(token, function(error) { 

 var publisherOptions = {
  insertMode: 'append',
  width: 150,
  height: 150,
  publishAudio:true, 
  publishVideo:true,
  name: "You"
};


 publisher = OT.initPublisher('mycam', publisherOptions);
 session.publish(publisher);
 });

 session.on("connectionCreated", function(event) {
   connectionCount++;
   displayConnectionCount();
});

session.on("connectionDestroyed", function(event) {
   connectionCount--;
   displayConnectionCount();
});

function displayConnectionCount() {
    document.getElementById("connectionCountField").value = connectionCount.toString();
    /*var newdata=connectionCount.toString();
      $.ajax({
            url:$('#baseUrl').val()+"home/updateactiveuser",
            type:'post',
            data: {newdata:newdata}
        })*/
}


 var enableVideo=true;

 function myFunction() {
 if(enableVideo)
 {
 publisher.publishVideo(false);
 enableVideo=false;
 } else
 {
 publisher.publishVideo(true);
 enableVideo=true;
 }
 }
 </script>


<?php 
});

$app->run();
}
?>

由于

2 个答案:

答案 0 :(得分:1)

以下是示例代码。我没有用过这个SLIM。但这也可以用Slim完成。我已经执行了5次脚本&amp;每次我获得一个唯一的Session-Id。

收到会话ID -

Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ0NzU0NH5KNk9Gcy9FSktPSlUwdldUbURwazJ0Umd-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ3ODMzM35rWWU5NDV1ZjZPMGhLc3pCS3pRSERJY0h-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ5NTcwOX5kc0Q3NDBjQSthOWJaMEk1eUllU3dCY0t-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzUwNzExOH5NMEZuZWRyejBZYnZRVk1zSEczNldocmV-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzUxNzE3NH5Yc0hyMUlacmFqK25pVzhXNDI5NTV6eDB-QX4

Vanilla PHP脚本 -

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

require 'vendor/autoload.php';
use OpenTok\OpenTok;

$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);

use OpenTok\MediaMode;
use OpenTok\ArchiveMode;


// An automatically archived session:
$sessionOptions = array(
    'archiveMode' => ArchiveMode::ALWAYS,
    'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);


// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();


echo "Session Id Got : $sessionId";

SLIM版本 -

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;

require 'vendor/autoload.php';

$app = new \Slim\App;

$container = $app->getContainer();

$container['opentok'] = function ($c) {
    $apiKey = '45833942';
    $apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';

    $opentok = new OpenTok($apiKey, $apiSecret);
    return $opentok;
};


$app->get('/', function (Request $request, Response $response) {
    // An automatically archived session:
    $sessionOptions = array(
        'archiveMode' => ArchiveMode::ALWAYS,
        'mediaMode' => MediaMode::ROUTED
    );
    $session = $this->opentok->createSession($sessionOptions);

    // Store this sessionId in the database for later use
    $sessionId = $session->getSessionId();

    $response->getBody()->write("Session Id Got : $sessionId");
    return $response;
});

$app->run();

希望,它会帮助你。

参考:https://tokbox.com/developer/sdks/php/

答案 1 :(得分:0)

您似乎已将代码基于OpenTok Hello World PHP sample。为了演示目的,编写此示例仅支持单个会话。这里的问题是你每次从缓存中检索相同的密钥(sessionId,这就是样本的作用。

你很亲密。将此示例扩展到多个会话的最简单方法是将新会话ID作为不同的密钥存储在缓存中。您需要更改代码以使用不同的密钥来存储和检索会话ID。因此,您可以从以下位置更改缓存检索逻辑:

<?php
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
  # ...
}
?>

类似于:

<?php
# Here we add `$id` from the URI segment to create a unique key
# Notice the change in the key name to `'session' . $id'`
$sessionId = $app->cache->getOrCreate('session' . $id, array(), function() use ($app) {
  # ...
}
?>

最简单的说,您的代码需要在内部将应用程序的实时聊天ID映射到OpenTok会话。每当您请求新的实时聊天ID时,它将创建一个新的OpenTok会话并在内部为该实时聊天ID存储新的OpenTok会话ID。

因此,如果您要求,您应该有两个不同的会话:

  • /home/livechat/foo/bar
  • /home/livechat/baz/bar

加成

创建OpenTok会话的快速提示:这就是使用OpenTok PHP SDK创建新会话所需的全部内容:

<?php
use OpenTok\OpenTok;
$apiObj = new OpenTok($API_KEY, $API_SECRET);

# This function creates an OpenTok session and returns a new session ID
function createOTSession() {
  $session = $apiObj->createSession(array('mediaMode' => MediaMode::ROUTED));
  return $session->getSessionId();
}
?>

每次调用$apiObj->createSession()时,它都会创建一个新会话,您可以通过在返回的对象上调用getSessionId()来访问会话ID。如果您具有上述createOTSession()之类的功能,则可以从需要创建新会话的路由中调用该功能。

请参阅:Creating OpenTok sessions in PHP