媒体处理这部分的视频转码涉及到 阿里云服务的对象存储OSS服务,消息服务MNS,及媒体处理MTS服务
可以利用阿里云服务的MTS服务即媒体处理 https://mts.console.aliyun.com/?spm=5176.8466032.aliyun_sidebar.aliyun_sidebar_mts.25181450XajZUr#/home/index
我们需要 通过学习 https://help.aliyun.com/document_detail/29208.html?spm=5176.2020520107.104.1.449f4ecbltS5na 转码教程,分别去完成工作流和管道的设置
登录我们的阿里云账户 进入之后如果要分配权限 则
根据转码文档 把该配的配好,然后进入如下
package com.huankeyun.community.service;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.mts.model.v20140618.QueryMediaListRequest;
import com.aliyuncs.mts.model.v20140618.QueryMediaListResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.huankeyun.core.api.file.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import static org.bouncycastle.crypto.tls.ConnectionEnd.client;
/**
* @Author zhaomengxia
* @create 2019/6/3 13:49
*/
@Service
@Slf4j
public class AliyunVideoService {
@Resource
private FileService fileService;
//步骤1.请填写你所需访问的Region:cn-hangzhou、cn-shenzhen、cn-shanghai、cn-beijing
private final String REGION = "cn-hangzhou";
//步骤2.从阿里云消息服务的控制台对应区域Copy MNSEndPoint
//MNS控制台链接:https://mns.console.aliyun.com
private final String mnsEndPoint = "https://1925320941993541.mns.cn-hangzhou.aliyuncs.com/";
private final String mtsEndpoint = "mts." + REGION + ".aliyuncs.com";
//步骤3.填写您的AK,确保此AK具有访问MTS的权限(即已经开通MTS)
private String accessKeyId = "LTAIaiadWrm2lhGR";
private String accessKeySecret = "CUr5jkEvKIA96c2bpSI7JK4fVj3etE";
//步骤4.填写您的媒体工作流输入Bbucket,务必与创建媒体工作流时设置的保持一致
//步骤5.填写媒体工作流处理视频完成时消息发送队列,务必与创建媒体工作流时设置的保持的一致
private String mediaWorkflowQueueName = "queue";
private CloudAccount account;
private CloudQueue queue;
private DefaultAcsClient aliyunClient;//调用MTS API的Client
@Autowired
public AliyunVideoService() {
this.account = new CloudAccount(accessKeyId, accessKeySecret, mnsEndPoint);
MNSClient mnsClient = account.getMNSClient();
this.queue = mnsClient.getQueueRef(mediaWorkflowQueueName);
try {
DefaultProfile.addEndpoint(REGION, REGION, "Mts", mtsEndpoint);
} catch (ClientException e) {
System.out.print(ExceptionUtils.getStackTrace(e));
System.exit(1);
}
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile(REGION, accessKeyId, accessKeySecret));
}
public List videoUrls() {
//步骤6.上传视频到媒体工作流处理Bucket,媒体工作流将自动启动处理此视频
//进入MTS控制台:https://mts.console.aliyun.com/
//进入媒体库设置->工作流,务必确保媒体工作流处于启动状态,否则媒体工作流不会处理此视频
List urls = new ArrayList<>();
//步骤7.等待媒体工作流消息回调汇报转码完成,
while (true) {
List messageList = queue.batchPopMessage(16, 30);
if (null == messageList || messageList.isEmpty()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
} else {
for (Message message : messageList) {
urls.addAll(handlingMessage(message));
}
return urls;
}
}
}
public List handlingMessage(Message message) {
String messageBody = message.getMessageBody();
ActivityDTO activityDTO = JSONObject.parseObject(messageBody, ActivityDTO.class);
List urls = new ArrayList<>();
if (activityDTO.getType().equals(ActivityType.Start.name())) {
//若工作流启动消息不希望处理,则直接删除
queue.deleteMessage(message.getReceiptHandle());
} else if (activityDTO.getType().equals(ActivityType.Report.name())) {
//System.out.print(JSONObject.toJSONString(activityDTO));
//获取媒体工作流执行信息
MediaWorkflowExecutionDTO mediaWorkflowExecutionDTO = activityDTO.getMediaWorkflowExecutionDTO();
//从媒体工作流中取活动列表
List activityDTOS = mediaWorkflowExecutionDTO.getActivities();
//遍历活动列表,判断转码是否成功
if (null != activityDTOS) {
for (ActivityDTO activity : activityDTOS) {
if (activity.getType().equals(ActivityType.Transcode.name())) {
if (activity.getState().equals(ActivityState.Success.name())) {
System.out.println("transcode activity:" + activity.getName() + " is success!");
} else {
System.out.println("---------dsjkdlhnsa");
continue;
}
}
}
}
//获取转码输出地址(OSS地址)
QueryMediaListRequest request = new QueryMediaListRequest();
request.setMediaIds(mediaWorkflowExecutionDTO.getMediaId());
request.setIncludePlayList(true);
try {
QueryMediaListResponse response = aliyunClient.getAcsResponse(request);
List list = response.getMediaList();
QueryMediaListResponse.Media media = list.get(0);
if (media.getPublishState().equals(MediaState.Published.name())) {
List playList = media.getPlayList();
if (null != playList) {
for (QueryMediaListResponse.Media.Play play : playList) {
//遍历转码输出地址
System.out.println(play.getFile1().getURL());
urls.add(play.getFile1().getURL());
}
}
}
} catch (ServerException e) {
System.out.print(ExceptionUtils.getStackTrace(e));
System.exit(1);
} catch (ClientException e) {
System.out.print(ExceptionUtils.getStackTrace(e));
System.exit(1);
}
//如果是report消息,需要从队列中删除,否则会一直在队列中
queue.deleteMessage(message.getReceiptHandle());
}
return urls;
}
public FileDTO uploadVideoFileToMediaWOrkflowInputBucket(String filePath) {
return fileService.uploadLocalFile(filePath);
}
}
其中的fileService里的uploadLocalFile(String filePath)方法为
public UploadResponse uploadFile(String category, MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
if (category.equals("video")) {
String fileType = filename.substring(filename.lastIndexOf("."), filename.length());
VideoType videoType = VideoType.getFormat(fileType);
if (null == videoType) {
throw new UnifiedException("不支持此视频格式!");
}
}
String key = KeyGenerateStrategy.MonthBased.key(category, filename);
String contentType = file.getContentType();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(contentType);
metadata.addUserMetadata(FILE_NAME, filename);
oss.putObject(bucket, key, file.getInputStream(), metadata);
AliyunOssUrl ossUrl = new AliyunOssUrl(bucket, key);
if (category.equals("video")) {
uploadLocalFile(ossUrl.httpsProtocol());
aliyunVideoService.videoUrls();
List strings = aliyunVideoService.videoUrls();
if (strings.size() > 0) {
int t = strings.size();
String s = strings.get(t - 1);
return new UploadResponse(filename, s);
}
else{
return uploadFile("video",file);
}
}
return new UploadResponse(filename, ossUrl.httpsProtocol());
}
/**
* //步骤6.上传视频到媒体工作流处理Bucket,媒体工作流将自动启动处理此视频
//进入MTS控制台:https://mts.console.aliyun.com/
//进入媒体库设置->工作流,务必确保媒体工作流处于启动状态,否则媒体工作流不会处理此视频
* @param filePath
* @return
*/
public FileDTO uploadLocalFile(String filePath) {
OSSClient client = new OSSClient(endpoint, accessKeyId, secretAccessKey);
String filename = this.getFilename(filePath);
return new FileDTO(client.getBucketLocation(bucket), bucket, filename);
}