点播播放
就是获取到文件id和appID就能实现播放
继上篇上传视频 https://www.cnblogs.com/rzkwz/p/15396582.html
在线获取视频预览
注意:播放前提需要在上传任务流模板
腾讯云提供了通过客户端上传签名 中的procedure参数,指定视频上传后要执行的任务
js
var getSignature = function(callback) {
$.ajax({
url : "getSign", //服务器获取客户端上传签名的URL
type : "POST",
success:function(data){
var dataObj = eval("(" + data + ")");
callback(dataObj.signature);
}
});
};
getSin.class
@RequestMapping("/getSign")
@ResponseBody
public String getSign() {
logger.info("获取签名中...");
//得到Sign
Signature sign = new Signature();
//个人API密钥中的Secret Id
sign.setSecretId(accessKeyId);
//个人API密钥中的Secret Key
sign.setSecretKey(accessKeySecret);
sign.setCurrentTime(System.currentTimeMillis() / 1000);
sign.setRandom(new Random().nextInt(java.lang.Integer.MAX_VALUE));
sign.setSignValidDuration(3600 * 24 * 2);
String signature = null;
try {
JSONObject jsonObject = new JSONObject();
signature = sign.getUploadSignature();
System.out.println("signature : " + signature);
jsonObject.put("signature",signature);
logger.info("返回签名中--end");
return jsonObject.toString();
} catch (Exception e) {
System.out.print("获取签名失败");
logger.info("获取签名失败");
e.printStackTrace();
return null;
}
}
Signature.class
在任务流处可以添加你所需的参数
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Signature {
private String secretId;
private String secretKey;
private long currentTime;
private int random;
private int signValidDuration;
private static final String HMAC_ALGORITHM = "HmacSHA1";
private static final String CONTENT_CHARSET = "UTF-8";
public static byte[] byteMerger(byte[] byte1, byte[] byte2) {
byte[] byte3 = new byte[byte1.length + byte2.length];
System.arraycopy(byte1, 0, byte3, 0, byte1.length);
System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
return byte3;
}
public String getUploadSignature() throws Exception {
String strSign = "";
String contextStr = "";
long endTime = (currentTime + signValidDuration);
contextStr += "secretId=" + java.net.URLEncoder.encode(secretId, "utf8");
contextStr += "¤tTimeStamp=" + currentTime;
contextStr += "&expireTime=" + endTime;
contextStr += "&random=" + random;
//任务流 视频转流
contextStr += "&procedure=" + "LongVideoPreset";
contextStr += "&taskPriority=" + 10;
contextStr += "&taskNotifyMode=" + "Finish";
try {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(this.secretKey.getBytes(CONTENT_CHARSET), mac.getAlgorithm());
mac.init(secretKey);
byte[] hash = mac.doFinal(contextStr.getBytes(CONTENT_CHARSET));
byte[] sigBuf = byteMerger(hash, contextStr.getBytes("utf8"));
strSign = new String(new BASE64Encoder().encode(sigBuf).getBytes());
strSign = strSign.replace(" ", "").replace("
", "").replace("
", "");
} catch (Exception e) {
throw e;
}
return strSign;
}
public void setSecretId(String secretId) {
this.secretId = secretId;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
public void setRandom(int random) {
this.random = random;
}
public void setSignValidDuration(int signValidDuration) {
this.signValidDuration = signValidDuration;
}
}
contextStr += "&procedure=" + "LongVideoPreset"; 对应任务流名称
进入正题获取播放地址
使用腾讯云视立方 Web 超级播放器(TCPlayer)
https://cloud.tencent.com/document/product/266/58804
引入js
<link href="https://web.sdk.qcloud.com/player/tcplayer/release/v4.2.1/tcplayer.min.css" rel="stylesheet">
<!--如果需要在 Chrome 和 Firefox 等现代浏览器中通过 H5 播放 HLS 格式的视频,需要在 tcplayer.v4.2.min.js 之前引入 hls.min.0.13.2m.js。-->
<script src="https://web.sdk.qcloud.com/player/tcplayer/release/v4.2.1/libs/hls.min.0.13.2m.js"></script>
<!--播放器脚本文件-->
<script src="https://web.sdk.qcloud.com/player/tcplayer/release/v4.2.1/tcplayer.v4.2.1.min.js"></script>
设置播放器容器
<video id="player-container-id" width="414" height="270" preload="auto" playsinline webkit-playsinline>
</video>
初始化代码
var player = TCPlayer('player-container-id', { // player-container-id 为播放器容器 ID,必须与 html 中一致
fileID: '5285890799710670616', // 请传入需要播放的视频 fileID(必须)
appID: '' // 请传入点播账号的 appID(必须)
});
功能
GetRequest()方法的作用是:采用的是get方法跳转到新的html页面,地址栏上有该视频的id,该方法就是获取到地址栏的id,然后再 传到TCPlayer()方法里面
具体可见 https://www.cnblogs.com/rzkwz/p/15384713.html
appID = '${appID}';
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
}
}
return theRequest;
}
//调用
var Request = new Object();
Request = GetRequest();
var fileID;
fileID = Request['resPid'];
var player = TCPlayer('player-container-id', { // player-container-id 为播放器容器ID,必须与html中一致
fileID: fileID, // 请传入需要播放的视频filID 必须
appID: appID, // 请传入点播账号的appID 必须
playbackRates: [0.5, 1, 1.25, 1.5, 2],
//其他参数请在开发文档中查看
plugins: {
VttThumbnail: {
// 'imgUrl': '//imgcache.qq.com/open/qcloud/video/tcplayer/examples/vod/7447398155146701990.jpg', // 传入预览图地址 非必须
'vttUrl': '' // 传入vtt文件地址
},
ContinuePlay: {
// auto: true, //[可选] 是否在视频播放后自动续播
// text: '上次播放至 ', //[可选] 提示文案
// btnText: '恢复播放' //[可选] 按钮文案
},
ProgressMarker: true,
ContextMenu: {
statistic: true,
levelSwitch: {
open: true, // 打开切换提示
// switchingText: '开始', // 开始切换时文案
// switchedText: '成功', // 切换成功时文案
// switchErrorText: '失败', // 切换失败时文案
}
}
}
});
</script>
下载
流程: 前端传参资源id请求后端接口 ---> 后端使用腾讯云SDK去获取视频地址然后返回前端 --->前端获取地址创建a标签下载该视频
getVideoInfo.class
/**
*
* Title: 获取视频播放地址
* Description: 获取视频播放地址
* @param resPid 用户号码
* @return
*/
@ResponseBody
@RequestMapping("/getVideoInfo")
public String getVideoInfo(String resPid){
logger.info("获取视频播放地址resPid:"+resPid);
String videoJSON="";
String mediaInfo = "";
JSONArray jsonArray = null;
try {
videoJSON = VodClient.getDescribeMediaInfos(accessKeyId, accessKeySecret, resPid);
JSONObject jsonObject = JSONObject.parseObject(videoJSON);
JSONArray jsonObjectJSONArray = jsonObject.getJSONArray("MediaInfoSet");
JSONObject basicInfo = jsonObjectJSONArray.getJSONObject(0).getJSONObject("BasicInfo");
return basicInfo.toString();
} catch (Exception e) {
logger.info("获取视频播放地址--异常:"+e);
e.printStackTrace();
}
logger.info("获取视频播放地址 --/getVideoInfo--end");
return videoJSON;
}
获取视频播放信息
该接口可在腾讯云API3.0调试获取
/**
* 获取视频播放信息
* @param secret_id
* @param secret_key
* @param videoId
* @return
*/
public static String getDescribeMediaInfos(String secret_id, String secret_key, String videoId) {
VodClient.secret_id = secret_id;
VodClient.secret_key = secret_key;
try {
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
Credential cred = new Credential(secret_id, secret_key);
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("vod.tencentcloudapi.com");
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
VodClient client = new VodClient(cred, "", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
String[] fileIds1 = {videoId};
req.setFileIds(fileIds1);
// 返回的resp是一个DescribeMediaInfosResponse的实例,与请求对象对应
DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
// 输出json格式的字符串回包
System.out.println(DescribeMediaInfosResponse.toJsonString(resp));
return DescribeMediaInfosResponse.toJsonString(resp);
} catch (TencentCloudSDKException e) {
System.out.println(e.toString());
}
return null;
}
前端js代码
downloadVideo:function(resPid){
$.ajax({
url : 'getVideoInfo',
data : {
resPid :resPid
},
dataType: "json",
success:function(data) {
//下载视频
fetch(data.MediaUrl).then(res => res.blob()).then(blob => {
const a = document.createElement('a');
document.body.appendChild(a)
a.style.display = 'none'
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download =data.Name;
a.click();
document.body.removeChild(a)
window.URL.revokeObjectURL(url);
});
}
});
},
查看下载接结果
可看到浏览器就下载下来