一 后端获取播放凭证
1 web层
@Api(description = "阿里云视频点播")
@CrossOrigin // 跨域
@RestController
@RequestMapping("/api/vod/media")
@Slf4j
public class ApiMediaController {
@Autowired
private VideoService videoService;
/**
* 功能描述:根据阿里云视频id获得视频凭证
*
* @param videoSourceId 阿里云视频id
* @return R 返回给前端的数据
* @author cakin
* @date 2020/12/19
*/
@GetMapping("get-play-auth/{videoSourceId}")
public R getPlayAuth(@ApiParam(value = "阿里云视频文件的id", required = true) @PathVariable String videoSourceId) {
try {
String playAuth = videoService.getPlayAuth(videoSourceId);
return R.ok().message("获取播放凭证成功").data("playAuth", playAuth);
} catch (Exception e) {
log.error(ExceptionUtils.getMessage(e));
throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR);
}
}
}
2 service层
接口
/**
* 功能描述:根据 阿里云视频id获得播放凭证
*
* @author cakin
* @date 2020/12/19
* @param videoSourceId 阿里云视频id
* @return String 视频凭证
*/
String getPlayAuth(String videoSourceId) throws ClientException;
实现
/**
* 功能描述:根据 阿里云视频id获得播放凭证
*
* @param videoSourceId 阿里云视频id
* @return String 视频凭证
* @author cakin
* @date 2020/12/19
*/
@Override
public String getPlayAuth(String videoSourceId) throws ClientException {
// 获取客户端
DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
vodProperties.getKeyid(),
vodProperties.getKeysecret());
// 创建请求对象
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
// 设置请求参数
request.setVideoId(videoSourceId);
// 发送请求得到响应
GetVideoPlayAuthResponse response = client.getAcsResponse(request);
return response.getPlayAuth();
}
二 前端播放器整合
1 api
// 从后端获取播放凭证
getPlayAuth(vid) {
return request({
baseURL: 'http://localhost:8130',
url: `/api/vod/media/get-play-auth/${vid}`,
method: 'get'
})
}
2 点击播放超链接
<a :href="'/player/'+video.videoSourceId" :title="video.title" target="_blank">
<span v-if="Number(course.price) !== 0 && video.free===true" class="fr">
<i class="free-icon vam mr10">免费试听</i>
</span>
<em class="lh-menu-i-2 icon16 mr5"> </em>{{ video.title }}
</a>
3 播放页脚本
<script>
import courseApi from '~/api/course'
export default {
async asyncData(page) {
// 得到视频id
const vid = page.route.params.vid
// console.log(vid)
// 根据视频id获取播放凭证
const response = await courseApi.getPlayAuth(vid)
return {
vid: vid,
playauth: response.data.playAuth
}
},
// 页面渲染之后执行
mounted() {
/* eslint-disable no-undef */
new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
vid: this.vid,
playauth: this.playauth,
encryptType: 1 // 当播放私有加密流时需要设置。
}, function(player) {
console.log('播放器创建好了。')
})
}
}
</script>
4 播放模板
<template>
<div>
<link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.2/skins/default/aliplayer-min.css" >
<script charset="utf-8" src="https://g.alicdn.com/de/prismplayer/2.8.2/aliplayer-min.js"/>
<!-- 阿里云视频播放器组件 -->
<script charset="utf-8" src="https://player.alicdn.com/aliplayer/presentation/js/aliplayercomponents.min.js"/>
<!-- 播放器 -->
<div id="J_prismPlayer" class="prism-player"/>
</div>
</template>
三 测试