视频直播生成推流和播放地址的PHP代码示例

视频直播生成推流和播放地址的PHP代码示例

更新时间:2020-06-23 10:38:51

概述

直播推流地址和播放地址本身没有API接口,需要在客户端自行拼接地址,然后使用推流工具或者播放器对其推流或播放。本文主要介绍如何生成直播的推流以及播放地址。

详细信息

视频直播生成推流和播放地址的PHP示例代码如下所示。

?php

function push_url($push_domain,$push_key,$expireTime,$appName,$streamName){

        $push_url = '';
        //未开启鉴权Key的情况下
        if($push_key==''){
                $push_url = 'rtmp://'.$push_domain.'/'.$appName.'/'.$streamName;
                echo $push_url;
                return;
        }
        $timeStamp = time() + $expireTime;
        $sstring = '/'.$appName.'/'.$streamName.'-'.$timeStamp.'-0-0-'.$push_key;
        $md5hash = md5($sstring);
        $push_url = 'rtmp://'.$push_domain.'/'.$appName.'/'.$streamName.'?auth_key='.$timeStamp.'-0-0-'.$md5hash;
        echo $push_url;
        echo PHP_EOL;
        return;
}

function play_url($play_domain,$play_key,$expireTime,$appName,$streamName){
        //未开启鉴权Key的情况下
        if($play_key==''){
                $rtmp_play_url = 'rtmp://'.$play_domain.'/'.$appName.'/'.$streamName;
                $flv_play_url = 'http://'.$play_domain.'/'.$appName.'/'.$streamName.'.flv';
                $hls_play_url = 'http://'.$play_domain.'/'.$appName.'/'.$streamName.'.m3u8';
        }else{
                $timeStamp = time() + $expireTime;

                $rtmp_sstring = '/'.$appName.'/'.$streamName.'-'.$timeStamp.'-0-0-'.$play_key;
                $rtmp_md5hash = md5($rtmp_sstring);
                $rtmp_play_url = 'rtmp://'.$play_domain.'/'.$appName.'/'.$streamName.'?auth_key='.$timeStamp.'-0-0-'.$rtmp_md5hash;

                $flv_sstring = '/'.$appName.'/'.$streamName.'.flv-'.$timeStamp.'-0-0-'.$play_key;
                $flv_md5hash = md5($flv_sstring);
                $flv_play_url = 'http://'.$play_domain.'/'.$appName.'/'.$streamName.'.flv?auth_key='.$timeStamp.'-0-0-'.$flv_md5hash;

                $hls_sstring = '/'.$appName.'/'.$streamName.'.m3u8-'.$timeStamp.'-0-0-'.$play_key;
                $hls_md5hash = md5($hls_sstring);
                $hls_play_url = 'http://'.$play_domain.'/'.$appName.'/'.$streamName.'.m3u8?auth_key='.$timeStamp.'-0-0-'.$hls_md5hash;
        }

        echo 'rtmp播放地址: '.$rtmp_play_url;
        echo PHP_EOL;
        echo 'flv播放地址: '.$flv_play_url;
        echo PHP_EOL;
        echo 'hls播放地址: '.$hls_play_url;
        echo PHP_EOL;
        return;
}
//推流域名
$push_domain = 'testpush.cn';
//推流域名配置的鉴权Key
$push_key = 'test_Push_key';
//生成随机的AppName
$appName = md5(uniqid(microtime(true),true));
//生成随机的StreamName
$streamName = md5(uniqid(microtime(true),true));
//配置过期时间为1小时
$expireTime = 3600;
//播放域名
$play_domain = 'testPlay.cn';
//播放域名配置的鉴权Key
$play_key = 'test_play_key';
push_url($push_domain,$push_key,$expireTime,$appName,$streamName);
play_url($play_domain,$play_key,$expireTime,$appName,$streamName);
?>

适用于

  • 视频直播