当前位置:网站首页>Alibaba Cloud video on demand + project combat
Alibaba Cloud video on demand + project combat
2022-07-30 22:32:00 【Fairy wants to carry】
目录
场景:
There are many functions,Video can be encrypted,防止盗链,并且节省了资源,Overrides the acceleration node,安全系数高


流程:
- 用户获取上传授权.
- VoD下发 上传地址和凭证 及 VideoId.
- 用户上传视频保存视频ID(VideoId).
- 用户服务端获取播放凭证.
- VoD下发带时效的播放凭证.
- 用户服务端将播放凭证下发给客户端完成视频播放.

设置转码格式

配置域名



项目实战
配置文件
<dependencies>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-sdk-vod-upload</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies># 服务端口
server.port=8003
# 服务名
spring.application.name=service-vod
# 环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 vod
#不同的服务器,地址不同
aliyun.vod.file.keyid=your accessKeyId
aliyun.vod.file.keysecret=your accessKeySecret
# 最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB
# 最大置总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB启动类
package com.guli.vod;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan(basePackages={"com.atguigu"})
public class VodApplication {
public static void main(String[] args) {
SpringApplication.run(VodApplication.class, args);
}
}整合阿里云Vod实现视频上传
1.Create a constant class to read the VOD key configured by the configuration file
package com.guli.vod.util;
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${aliyun.vod.file.keyid}")
private String keyId;
@Value("${aliyun.vod.file.keysecret}")
private String keySecret;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
@Override
public void afterPropertiesSet() throws Exception {
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
}
}2.创建一个VodClient客户端
through regional nodes,keyand key to shape a clientclient
package com.atguigu.vod.Utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
public class InitVodClient {
//填入AccessKey信息
public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
String regionId = "cn-shanghai"; // 点播服务接入地域
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
}
3.创建Service接口,And create the corresponding business logic
package com.guli.vod.service;
public interface VideoService {
String uploadVideo(MultipartFile file);
}4.业务类,上传视频到阿里云
根据我们的demo写法就行,1.The first is to get the name of the uploaded file,Define a stream——>2.然后将key和密钥,文件名称,流封装到UploadStreamRequest中——>3.根据UploadVideoImplDefined uploadapi:uploadStream()Encapsulate the request and get the responseUploadStreamResponse——>4.Finally, determine the response status,返回响应的vido的id
删除阿里云视频,业务类似,Just use itrequestThe request is no longer an upload,use to delete
package com.atguigu.vod.service.impl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.eduservice.R;
import com.atguigu.eduservice.exceptionHandler.GuliException;
import com.atguigu.vod.Utils.ConstantVodUtils;
import com.atguigu.vod.Utils.InitVodClient;
import com.atguigu.vod.service.VodService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;
@Service
public class VodServiceImpl implements VodService {
/**
* 上传视频到阿里云
* @param file
* @return
*/
@Override
public String uploadVideoAly(MultipartFile file) {
try {
//accessKeyId, accessKeySecret
//fileName:上传文件原始名称
String fileName = file.getOriginalFilename();
//title:上传之后显示名称
String title = fileName.substring(0, fileName.lastIndexOf("."));
//inputStream:上传文件输入流
InputStream inputStream = file.getInputStream();
UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadStreamResponse response = uploader.uploadStream(request);
String videoId = null;
if (response.isSuccess()) {
videoId = response.getVideoId();
} else { //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码.其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因
videoId = response.getVideoId();
}
return videoId;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Delete multiple cloud videos
* @param videoIdList
*/
@Override
public void removeMoreAlyVideo(List<String> videoIdList) {
try {
//初始化对象(Connect to our cloud client)
DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
//创建删除视频的request对象
DeleteVideoRequest request = new DeleteVideoRequest();
//将videoIdList值转为1,2,3这种
String videoIds = StringUtils.join(videoIdList.toArray(), ",");
//然后向request设置视频id
request.setVideoIds(videoIds);
//返回response
client.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
throw new GuliException(20001,"删除视频失败");
}
}
}
5.控制层
package com.atguigu.vod.controller;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.eduservice.R;
import com.atguigu.eduservice.exceptionHandler.GuliException;
import com.atguigu.vod.Utils.ConstantVodUtils;
import com.atguigu.vod.Utils.InitVodClient;
import com.atguigu.vod.service.VodService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Api(description = "上传视频")
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class CodController {
@Autowired
private VodService vodService;
/**
* 1.上传视频到阿里云
*/
@PostMapping("uploadAlyiVideo")
public R uploadAlyiVideo(MultipartFile file){
String vodId=vodService.uploadVideoAly(file);
return R.ok().data("vodId",vodId);
}
/**
* 2.根据id删除阿里云视频
* 这里需要注意,We just deleted the Alibaba Cloud stuff,If the video inside the subsection in the databaseidTo delete it, you need to think about calling the interface on the front end
*/
@DeleteMapping("removeAlyVideo/{id}")
public R removeAlyVideo(@PathVariable String id){
try {
//初始化对象(Connect to our cloud client)
DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
//创建删除视频的request对象
DeleteVideoRequest request = new DeleteVideoRequest();
//然后向request设置视频id
request.setVideoIds(id);
//返回response
client.getAcsResponse(request);
return R.ok();
} catch (ClientException e) {
e.printStackTrace();
throw new GuliException(20001,"删除视频失败");
}
}
/**
* 3.删除多个阿里云视频
* 参数:多个视频id
*/
@DeleteMapping("delete-batch")
public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList){
vodService.removeMoreAlyVideo(videoIdList);
return R.ok();
}
/**
* 4.根据视频id获取视频凭证
*/
@GetMapping("getPlayAuth/{vid}")
public R getPlayAuth(@PathVariable String vid){
try {
//1.初始化对象client
DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
//2.创建获取凭证的request和resp对象
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
//3.向req中设置视频id
request.setVideoId(vid);
//4.调用方法得到凭证
GetVideoPlayAuthResponse response = client.getAcsResponse(request);
String playAuth = response.getPlayAuth();
return R.ok().data("playAuth",playAuth);
} catch (Exception e) {
throw new GuliException(20001,"获取凭证失败");
}
}
}
整合阿里云视频播放器
1.首先根据VodClient利用keyand the key to initialize oneclient——>2.Then define a get video credentialrequest,Inside the package videoid——>3.然后client通过这个reuqest请求得到response凭证——>4.最后根据response去getPlayAuthcredentials and respond
package com.guli.vod.controller;
@Api(description="阿里云视频点播微服务")
@CrossOrigin //跨域
@RestController
@RequestMapping("/vod/video")
public class VideoController {
@GetMapping("get-play-auth/{videoId}")
public R getVideoPlayAuth(@PathVariable("videoId") String videoId) throws Exception {
//获取阿里云存储相关常量
String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
//初始化
DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(accessKeyId, accessKeySecret);
//请求
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
request.setVideoId(videoId);
//响应
GetVideoPlayAuthResponse response = client.getAcsResponse(request);
//得到播放凭证
String playAuth = response.getPlayAuth();
//返回结果
return R.ok().message("获取凭证成功").data("playAuth", playAuth);
}
}前端方面
1.Click to enter thisurl,and incoming videoid,This video is also our section,Sections above are our chapters,Above the chapter is the course,层层封装,We only need to get our course information on the page to get chapters and videosid了
<ol class="lh-menu-ol" style="display: block">
<li
class="lh-menu-second ml30"
v-for="video in chapter.children"
:key="video.id"
>
<a
:href="'/player/' + video.videoSourceId"
target="_blank"
>
<span class="fr">
<i class="free-icon vam mr10">在线观看</i>
</span>
<em class="lh-menu-i-2 icon16 mr5"> </em
>{
{ video.title }}
</a>
</li>
</ol>2.从这个apiCall the background interface to obtain the video credential
const api_name = '/vod/video'
export default {
getPlayAuth(vid) {
return request({
url: `${api_name}/get-play-auth/${vid}`,
method: 'get'
})
}
}3.Create a playable page
<template>
<div>
<!-- 阿里云视频播放器样式 -->
<link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css" >
<!-- 阿里云视频播放器脚本 -->
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-min.js" />
<!-- 定义播放器dom -->
<div id="J_prismPlayer" class="prism-player" />
</div>
</template>4.Via an asynchronous method based on the videoid获取播放凭证
<script>
import vod from '@/api/vod'
export default {
layout: 'video',//应用video布局
asyncData({ params, error }) {
return vod.getPlayAuth(params.vid).then(response => {
// console.log(response.data.data)
return {
vid: params.vid,
playAuth: response.data.data.playAuth
}
})
}
}
</script>5.创建播放器
/**
* 页面渲染完成时:此时js脚本已加载,Aliplayer已定义,可以使用
* 如果在created生命周期函数中使用,Aliplayer is not defined错误
*/
mounted() {
new Aliplayer({
id: 'J_prismPlayer',
vid: this.vid, // 视频id
playauth: this.playAuth, // 播放凭证
encryptType: '1', // 如果播放加密视频,则需设置encryptType=1,非加密视频无需设置此项
width: '100%',
height: '500px'
}, function(player) {
console.log('播放器创建成功')
})
}其他选项
// 以下可选设置
cover: 'http://guli.shop/photo/banner/1525939573202.jpg', // 封面
qualitySort: 'asc', // 清晰度排序
mediaType: 'video', // 返回音频还是视频
autoplay: false, // 自动播放
isLive: false, // 直播
rePlay: false, // 循环播放
preload: true,
controlBarVisibility: 'hover', // 控制条的显示方式:鼠标悬停
useH5Prism: true, // 播放器类型:html5功能展示:阿里云Aliplayer播放器
边栏推荐
猜你喜欢
随机推荐
Difference between cookie and session
折叠旧版应用程序
WSL安装图形界面并通过xrdp/X-Launch访问
史上最全的Redis基础+进阶项目实战总结笔记
MySql 5.7.38 download and installation tutorial, and realize the operation of MySql in Navicat
2022.7.27
Go的Gin框架学习
TCP 连接 三次握手 四次挥手
StoneDB 为何敢称业界唯一开源的 MySQL 原生 HTAP 数据库?
Go1.18升级功能 - 模糊测试Fuzz 从零开始Go语言
设备树的引入与体验
Py's pdpbox: a detailed introduction to pdpbox, installation, and case application
IDEA2021.2安装与配置(持续更新)
二进制序列
MySQL user authorization
Py之pdpbox:pdpbox的简介、安装、案例应用之详细攻略
Go1.18升级功能 - 泛型 从零开始Go语言
[MySQL] Mysql transaction and authority management
DistSQL in-depth analysis: creating a dynamic distributed database
一文详解:SRv6 Policy模型、算路及引流









