阿里云的视频点播

  1. 首先在阿里云官网中找到视频点播控制台 , 开通视频点播服务阿里云的视频点播_第1张图片
  2. 参考阿里云官方使用说明文档
  3. 使用服务端sdk进行操作, 本文使用的事java SDK阿里云的视频点播_第2张图片
  4. 安装配置依赖到项目中
    4.1 添加仓库配置(可省略此步骤)
    <repositories>
      <repository>
        <id>sonatype-nexus-staging</id>
        <name>Sonatype Nexus Staging</name>
        <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
      </repository>
    </repositories>

4.2添加Jar包依赖
  <dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.3.3</version>
  </dependency>
  <dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-vod</artifactId>
    <version>2.15.5</version>
  </dependency>
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
  </dependency>
  1. 创建初始化类
package com.example.vod;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

public class InitObject {

    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;
    }

}

获取视频播放地址

  1. 创建初始化对象
  2. 创建获取视频地址request和response
  3. 向request对象里面设置视频id
  4. 调用初始化对象里面的方法传递request , 获取数据
//根据视频id获取视频播放地址
    public static void GetVodUrl() throws ClientException {
        //根据视频id获取视频地址
        //创建初始化对象
        DefaultAcsClient client = InitObject.initVodClient("LTAI4GCBSGzKJiT7dM2iK3Zu", "NYH0iN5pZvtEvO5DFwdfFWUnKdfI84");

        //创建获取视频地址request和response
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        GetPlayInfoResponse response = new GetPlayInfoResponse();

        //向request对象里面设置视频id
        request.setVideoId("95e8173688a44782b3257a4b224906c6");

        //调用初始化对象里面的方法传递request , 获取数据
        response = client.getAcsResponse(request);

        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        //播放地址
        for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
            System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
        }
        //Base信息
        System.out.print("VideoBase.Title = " + response.getVideoBase().getTitle() + "\n");
    }

获取视频播放凭证

  1. 获取视频凭证
//根据视频id获取视频的播放凭证
    public static void GetVodPinZheng() throws ClientException {
        //根据视频id获取视频地址
        //创建初始化对象
        DefaultAcsClient client = InitObject.initVodClient("LTAI4GCBSGzKJiT7dM2iK3Zu", "NYH0iN5pZvtEvO5DFwdfFWUnKdfI84");

        //创建获取视频凭证request和response
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();

        //向request设置视频id
        request.setVideoId("75599a5db0b34a5aacbbdc4c3d7dbdbe");

        //调用初始化对象里面的方法传递request , 获取数据
        response = client.getAcsResponse(request);

        System.out.println("PlayAuth" + response.getPlayAuth());

    }

上传视频到阿里云

  1. 上传视频
  2. 引入依赖
 <dependency>
   <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.3.3</version>
</dependency>
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-vod</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20170516</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-sdk-vod-upload</artifactId>
    <version>1.4.11</version>
</dependency>

由于这个依赖没有开源 , 所以无法通过maven仓库直接引入 , 下面是引入方式

先去阿里云官网下载sdk环境阿里云的视频点播_第3张图片

解压下载的文件 , 打开lib目录进入cmd命令行 , 输入这条命令

mvn install:install-file  -DgroupId=com.aliyun  -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.11 -Dpackaging=jar  -Dfile=aliyun-java-vod-upload-1.4.12.jar
  1. 写代码
//上传视频的方法
    public static void uploadVod(){
        String accessKeyId = "LTAI4GCBSGzKJiT7dM2iK3Zu";
        String accessKeySecret = "NYH0iN5pZvtEvO5DFwdfFWUnKdfI84";
        String title = "6 - What If I Want to Move Faster - upload by sdk";// 上传之后视频的名称
        String fileName = "G:/2020尚硅谷 在线教育 spring boot+springcloud分布式项目/资料/项目资料/1-阿里云上传测试视频/6 - What If I Want to Move Faster.mp4"; // 本地文件的路径和名称

        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上传时每个分片的大小,默认为2M字节 */
        request.setPartSize(2 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数,默认为1,(注:该配置会占用服务器CPU资源,需根据服务器情况指定)*/
        request.setTaskNum(1);

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            /* 如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }

删除阿里云视频

//根据视频id删除阿里云视频
    public static void removeAlyVideo(){
    	String accessKeyId = "LTAI4GCBSGzKJiT7dM2iK3Zu";
        String accessKeySecret = "NYH0iN5pZvtEvO5DFwdfFWUnKdfI84";
        
        //初始化对象
        DefaultAcsClient client = InitVodClient.initVodClient(accessKeyId , accessKeySecret );
        //创建删除视频的request对象
        DeleteVideoRequest request = new DeleteVideoRequest();
        //向request中设置视频id
        request.setVideoIds("59636e3f8e6a4ee3aa95e2eb65b0caf3");
        //调用初始化对象方法实现删除
        try {
            client.getAcsResponse(request);return R.ok();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

整合上传视频到项目中

  1. 引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>service</artifactId>
        <groupId>com.starcpdk.edu</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>service_vod</artifactId>

    <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>

</project>
  1. 配置application…properties
# 服务端口
server.port=8003

# 服务名
spring.application.name=service-vod

# 环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 vod
#不同的服务器,地址不同
aliyun.vod.file.keyid=LTAI4GCBSGzKJiT7dM2iK3Zu
aliyun.vod.file.keysecret=NYH0iN5pZvtEvO5DFwdfFWUnKdfI84

# 最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB

# 最大置总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB
**最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB**
 **最大置总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB**

这两块的配置是因为tomcat限制文件上传大小 , 通过这两个配置使得tomcat允许文件大文件上传
在http中配置 
client_max_body_size 1024m;

server {
        listen 9001;
        server_name localhost;

        location ~ /eduservice/ {
             proxy_pass http://localhost:8001;
        }

        location ~ /eduoss/ {
             proxy_pass http://localhost:8002;
        }
		
		location ~ /eduvod/ {           
			 proxy_pass http://localhost:8003;
		}

阿里云的视频点播_第4张图片
阿里云的视频点播_第5张图片
16. 书写工具类获取配置文件中的keyId 和 keySecret;

package com.starcpdk.edu.vod.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantVodUtils 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;
    }
}

  1. 编写controller
package com.starcpdk.edu.vod.controller;

import com.starcpdk.edu.commonutils.R;
import com.starcpdk.edu.vod.service.VodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(description = "视频管理")
@RestController
@CrossOrigin
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    @ApiOperation(value = "视频上传")
    //上传视频到阿里云
    @PostMapping("uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file){
        //返回视频上传后的视频id
        String videoId = vodService.uploadAlyVideo(file);
        return R.ok().data("videoId" , videoId);
    }
}

  1. 编写service层实现
package com.starcpdk.edu.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.starcpdk.edu.vod.service.VodService;
import com.starcpdk.edu.vod.utils.ConstantVodUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class VodServiceImpl implements VodService {

    //上传视频到阿里云

    /**
     * accessKeyId:id
     * accessKeySecret:秘钥
     * title:上传到阿里云的视频文件的名称
     * fileName:原始文件名称
     * inputStream:文件的输入流
     *
     * @param file
     * @return
     */


    @Override
    public String uploadAlyVideo(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        InputStream inputStream = null;
        String videoId = "";
        try {
            inputStream = file.getInputStream();
            System.out.println("文件流" + inputStream);
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);

            System.out.println("keyid:" + ConstantVodUtils.ACCESS_KEY_ID);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else { //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
                videoId = response.getVideoId();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return videoId;
    }
}

  1. 删除阿里云视频
//根据视频id删除阿里云视频
    @ApiOperation(value = "根据视频id删除阿里云视频")
    @DeleteMapping("removeAlyVideo/{id}")
    public R removeAlyVideo(@PathVariable String id){
        //初始化对象
        DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
        //创建删除视频的request对象
        DeleteVideoRequest request = new DeleteVideoRequest();
        //向request中设置视频id
        request.setVideoIds(id);
        //调用初始化对象方法实现删除
        try {
            client.getAcsResponse(request);
            return R.ok();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new MyException(20001 , "删除失败");
        }
    }

你可能感兴趣的:(阿里云的视频点播)