目录
整合阿里云Vod实现视频上传
整合阿里云视频播放器
前端方面
场景:
功能十分多,可以对视频进行加密,防止盗链,并且节省了资源,覆盖了加速节点,安全系数高
流程:
- 用户获取上传授权。
- 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.创建一个常量类读取配置文件配置的视频点播的密钥
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;@Overridepublic void afterPropertiesSet() throws Exception {ACCESS_KEY_ID = keyId;ACCESS_KEY_SECRET = keySecret;}
}
2.创建一个VodClient客户端
通过地域节点,key和密钥塑造一个客户端client
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接口,并创建对应的业务逻辑
package com.guli.vod.service;
public interface VideoService {String uploadVideo(MultipartFile file);
}
4.业务类,上传视频到阿里云
根据我们的demo写法就行,1.首先是得到上传文件的名称,定义一个流——>2.然后将key和密钥,文件名称,流封装到UploadStreamRequest中——>3.根据UploadVideoImpl定义的上传api:uploadStream()将请求封装起来得到响应UploadStreamResponse——>4.最后判断响应状态,返回响应的vido的id
删除阿里云视频,业务类似,只是说用的request请求不再是上传了,用的是删除
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*/@Overridepublic 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;}}/*** 删除多个云视频* @param videoIdList*/@Overridepublic void removeMoreAlyVideo(List<String> videoIdList) {try {//初始化对象(连接我们的云客户端)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设置视频idrequest.setVideoIds(videoIds);//返回responseclient.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 {@Autowiredprivate VodService vodService;/*** 1.上传视频到阿里云*/@PostMapping("uploadAlyiVideo")public R uploadAlyiVideo(MultipartFile file){String vodId=vodService.uploadVideoAly(file);return R.ok().data("vodId",vodId);}/*** 2.根据id删除阿里云视频* 这里需要注意,我们只是删除了阿里云的东西,如果数据库中小节里面的视频id要删除还需要再前端调用接口进行思考*/@DeleteMapping("removeAlyVideo/{id}")public R removeAlyVideo(@PathVariable String id){try {//初始化对象(连接我们的云客户端)DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);//创建删除视频的request对象DeleteVideoRequest request = new DeleteVideoRequest();//然后向request设置视频idrequest.setVideoIds(id);//返回responseclient.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.初始化对象clientDefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);//2.创建获取凭证的request和resp对象GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();//3.向req中设置视频idrequest.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利用key和密钥初始化一个client——>2.然后定义一个获取视频凭证的request,里面封装视频id——>3.然后client通过这个reuqest请求得到response凭证——>4.最后根据response去getPlayAuth凭证并且进行响应
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.点击之后进入这个url,并且传入视频的id,这个视频也就是我们的小节,小节上面是我们的章节,章节上面是课程,层层封装,我们只需要再页面中获取我们的课程信息就可以进而获取章节和视频id了
<ol class="lh-menu-ol" style="display: block"><liclass="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.从这个api中调用后台接口获取视频凭证
const api_name = '/vod/video'export default {getPlayAuth(vid) {return request({url: `${api_name}/get-play-auth/${vid}`,method: 'get'})}}
3.创建播放的页面
<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.通过异步方法根据视频id获取播放凭证
<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, // 视频idplayauth: 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播放器