Hi,为确保您的账号安全,请大家修改登陆密码为包含大小写字母、标点、数字的复合密码,不要使用过于简单的登陆密码。
您当前的位置:首页 :: PHP

laravel之阿里云视频点播篇

时间:2018-01-16 18:14:02  来源:  作者:

laravel之阿里云视频点播篇

项目需要使用阿里云视频点播与直播功能,那么我们主要讲点播功能,直接我们会讲一下实现原理,不废话先下载阿里云SDK,地址https://help.aliyun.com/document_detail/53111.html
github地址:https://github.com/aliyun/aliyun-openapi-php-sdk

下载完后这整合把laravel里,怎么整合方法有很多,这里不多说,不懂可以百度吧

我们主要讲核心的功能与实现下面这视频点播的介绍
https://help.aliyun.com/document_detail/60574.html?spm=5176.10609282.905295..7e8f8ba6ajIluw

自己可以先看看

上面的API下载完之后,整合laravel之后里,我们打开aliyun-php-sdk-core里的Config.php在这里我们可以跟据需要开启对应的功能模块,我们只开启

Autoloader::addAutoloadPath("aliyun-php-sdk-live");
Autoloader::addAutoloadPath("aliyun-php-sdk-vod");

然后打开aliyun-php-sdk-vod目录,有vod/Request/V20170321等这样的路径


下面是我的项目里的头,大家可以参照一下

<?php
namespace App\Repositories;
include_once app_path('Knowledge/AliyunOpenApi') . '/aliyun-php-sdk-core/Config.php';
use Illuminate\Http\Request;
use Config;
use vod\Request\V20170321 as vod;

......//此处省略2000code 
//去拿阿里云上传凭证 $data里的数据就是前端收集提交过来的,具体可以看下面使用的参数
public function aliyunUploadAuth($data){
    $liveConfig = Config::get('live.aliyun'); //去拿配置信息与阿里的APPID等
    $regionId = $liveConfig['region_id']; //具体的配置信息在下面
    $accessKeyId = $liveConfig['access_key'];
    $accessKeySecret = $liveConfig['access_key_secret'];
    $profile = \DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    $client = new \DefaultAcsClient($profile);

    $req = new vod\CreateUploadVideoRequest();
    $req->setAcceptFormat('JSON');
    $req->setRegionId($regionId);
    $req->setTitle($data['title']);
    //视频源文件名称(必须包含扩展名)
    $req->setFileName($data['filename']);
    //视频源文件字节数
    if($data['filename']){
        $req->setFileSize($data['filesize']);
    }
    //$request->setDescription("视频描述");
    //自定义视频封面URL地址
    //$request->setCoverURL("http://cover.sample.com/sample.jpg");
    //上传所在区域IP地址
    //$request->setIP("127.0.0.1");
    //$request->setTags("标签1,标签2");
    //视频分类ID
    //$req->setCateId($liveConfig['cateid']);
    //$request->setCateId(0);
    $response = $client->getAcsResponse($req);
    return $response;
}
//如果凭证过期,重新刷新凭证 这里需要videoid阿里返回的
public function refreshaliyunUploadAuth($videoid){
    $liveConfig = Config::get('live.aliyun');
    $regionId = $liveConfig['region_id'];
    $accessKeyId = $liveConfig['access_key'];
    $accessKeySecret = $liveConfig['access_key_secret'];
    $profile = \DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    $client = new \DefaultAcsClient($profile);

    $req = new vod\RefreshUploadVideoRequest();
    $req->setAcceptFormat('JSON');
    $req->setRegionId($regionId);
    $req->setVideoId($videoid);
    $response = $client->getAcsResponse($req);
    return $response;
}
//去阿里云拿播放凭证
public function aliyunPlayAuth($videoid){
    $liveConfig = Config::get('live.aliyun');
    $regionId = $liveConfig['region_id'];
    $accessKeyId = $liveConfig['access_key'];
    $accessKeySecret = $liveConfig['access_key_secret'];
    $profile = \DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    $client = new \DefaultAcsClient($profile);

    $req = new vod\GetVideoPlayAuthRequest();
    $req->setAcceptFormat('JSON');
    $req->setRegionId($regionId);
    $req->setVideoId($videoid);
    $response = $client->getAcsResponse($req);
    return $response;
}
//去阿里拿点播视频信息 含视频图片,转码状态等 这个就是可以查询上传视频的信息比如封面图片视频大小,转码信息等
public function aliyunVodInfo($videoid, $id=0){
    $liveConfig = Config::get('live.aliyun');
    $regionId = $liveConfig['region_id'];
    $accessKeyId = $liveConfig['access_key'];
    $accessKeySecret = $liveConfig['access_key_secret'];
    $profile = \DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    $client = new \DefaultAcsClient($profile);
    $alistatus = VideoCourseVod::$alistatus;

    $req = new vod\GetVideoInfoRequest();
    $req->setAcceptFormat('JSON');
    $req->setRegionId($regionId);
    $req->setVideoId($videoid);
    $res = $client->getAcsResponse($req);
    if(empty($id)){
        return $res;
    }
    if($res->Video){
        $data = [
            'total_time'=>round($res->Video->Duration),
            'cover' =>$res->Video->CoverURL,
            'status'=>$alistatus[$res->Video->Status],
            'size'  =>$res->Video->Size,
        ];
        //VideoVod::where('id', $id)->update($data);
        //我这里就是把查询的信息修改了
    }
    return $res;
}

//配置信息

'aliyun' => [
    'region_id' => 'cn-shanghai',
    'access_key' => env('ALIYUN_ACCESS_KEY'),
    'access_key_secret' => env('ALIYUN_ACCESS_KEY_SECRET'),
    // 推流域名
    'push_domain' => 'rtmp://video-center.alivecdn.com',
    // 鉴权key
    'auth_key' => 'XXXXXXXXXXXXXXXXXXXXXX',
    // 鉴权有效时间 单位秒
    'auth_timestamp' => '1800',
    // 鉴权rand 随机数,一般设成0
    'auth_rand' => '0',
    // 鉴权uid 暂未使用(设置成0即可)
    'auth_uid' => '0',
    // 播放域名
    'vhost' => 'video.upvup.com', //改成自己的播放域名
    // 播放类型 rtmp flv m3u8
    'play_type' => 'm3u8',
    // oss 专用 借用地方
    'end_point' => 'oss-cn-shanghai.aliyuncs.com',
    // 直播视频默认的分辨率
    'default_width' => '1280',
    'default_height' => '720',
    //'cateid' => '10000', //分类ID 阿里云后台查看

]

面前端的处理
视频上传选择页面bootstrap框架 样式自己按需要改吧

<div class="form-group">
    <label class="control-label col-sm-3">视频<span class="required-field">*</span></label>
    <div class="col-sm-3">
        <input class="form-control" type="text" id="videoid" name="videoid" data-rule-required="true"
               data-msg-required="请选择视频"/>
        <input type="hidden" id="filesize" name="filesize"/>
        <div class="input-group">
            <input type="file" id="upfile" name="upfile"/>
        </div>
        <div class="progress" style="display: none;">
            <div class="progress-bar progress-bar-success" role="progressbar" aria-valuemin="0"
                 aria-valuemax="100" style="width: 2%;">
                <span class="sr-only"></span>
            </div>
        </div>
    </div>
</div>

JS部分引入两个JS 可以下载最新版https://help.aliyun.com/document_detail/52204.html?spm=5176.doc53406.6.678.6GaIhn

/js/ali/aliyun-sdk.min.js
/js/ali/vod-sdk-upload-1.0.6.min.js
<script type="text/javascript">
	$(document).ready(function () {
	    var upinfo; //上传视频凭证变量

	    var uploader = new VODUpload({
	        'onUploadFailed': function (uploadInfo, code, message) {
	            //notify("提示", "上传失败", {type: "warning"});
	        },
	        'onUploadSucceed': function (uploadInfo) {
	            $('#videoid').val(upinfo.VideoId);
	            $('#filesize').val(uploadInfo.file.size);
	            //notify("提示", "上传成功,请等待服务器转码", {type: "success"});
	            //console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
	            //$('button.btn-save').removeattr('disabled'); //上传完成把提交按钮设置为可点击
	            //console.log(uploadInfo);
	        },
	        'onUploadProgress': function (uploadInfo, totalSize, uploadedSize) {
	        	//上传进度条处理
	            $('.progress-bar').css({'width': Math.ceil(uploadedSize * 100 / totalSize) + "%"});
	            //console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(uploadedSize * 100 / totalSize) + "%");
	        },
	        'onUploadTokenExpired': function () {
	        	//刷新凭证
	            //console.log("onUploadTokenExpired");
	            refreshuploadinfo();
	            uploader.resumeUploadWithAuth(upinfo.UploadAuth);
	        },
	        'onUploadstarted': function (uploadInfo) {
	        	//拿到凭证开始上传
	            uploader.setUploadAuthAndAddress(uploadInfo, upinfo.UploadAuth, upinfo.UploadAddress);
	            //console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
	        }

	    });

	    //拿上传凭证
	    function getuploadinfo(obj) {
	        $.ajax({
	            async: false,
	            type: 'post',
	            dataType: 'json',
	            url: '/vod/upload-info',
	            data: {title: $('#title').val(), filename: obj.files[0].name, filesize: obj.files[0].size},
	            error: function () {
	                //notifyFailed();
	            },
	            success: function (res) {
	            	//这里处量服务器返回的上传凭证数据一个json数据, [status,msg,data]
	                if (res.status > 0) {
	                    //notify("提示", res.msg, {type: "warning"});
	                } else {
	                    upinfo = res.data;
	                }
	            }
	        });
	    }

	    function refreshuploadinfo() {
	        $.ajax({
	            async: false,
	            type: 'post',
	            dataType: 'json',
	            url: '/vod/upload-info',
	            data: {videoid: upinfo.VideoId},
	            error: function () {
	                //notifyFailed();
	            },
	            success: function (res) {
	                if (res.status > 0) {
	                    //notify("提示", res.msg, {type: "warning"});
	                } else {
	                    //upinfo = res.data;
	                }
	            }
	        });
	    }

	    $('#upfile').on('change', function () {
	        if (!$('#title').val()) {
	            //notify("提示", "请输入标题", {type: "warning"});
	            $(this).val('');
	            return;
	        }
	        getuploadinfo(this);
	        if (upinfo) {
	            uploader.init();
	            var userData = '{"Vod":{"UserData":"{"IsShowWaterMark":"false","Priority":"7"}"}}';
	            uploader.addFile(this.files[0], null, null, null, userData);
	            $('.progress').show();
	            //$('button.btn-save').attr('disabled','disabled'); //上传的时候把提交的按钮设置为禁用
	            uploader.startUpload();
	        } else {
	            $(this).val('');
	        }

	    });
	    //....这里省略2000code 一些判断与表单提交等
	});


</script>

然后在后台列表的地址加上上面查询视频状态的地址或增加定时任务去查询视频转码状态,收工

举报
收藏0次 / 评论0
评论(0)
还可以输入 2000 个字符
还可以输入 2000 个字符
取消回复
举报×

还可以输入 264 字符

收藏(0)×