pom.xml
<! Aliyun </groupId> <artifactId>aliyun- Java - sdK-core </artifactId> < version > 4.4.8 < / version > < / dependency > < the dependency > < groupId > com. The aliyun < / groupId > < artifactId > aliyun - Java - SDK - facebody < / artifactId > < version > 1.1.1 < / version > < / dependency > <! <dependency> <groupId>org.bytedeco</groupId> <artifactId> Javacv-platform </artifactId> <version>1.4.4</version> </dependency>Copy the code
/** * in vivo detection *@paramFileUrl photo *@paramMessge Prompt message *@return* /
public Boolean VideoVivoDetection(String fileUrl,String messge){
try {
Results results = FaceRecognition.VideoVivoDetectionPhoto(fileUrl,messge);
Float faceConfidence = Float.valueOf(sysUserRoleMapper.getSysDictItem("In vivo detection - Face confidence."));// The confidence level is read from the data dictionary table to achieve dynamic adjustment
if(faceConfidence > results.getRate()){
throw new BadRequestException(messge + "[face confidence] is low, the system requires confidence is: [" + faceConfidence + "], this check confidence level [" + results.getRate() + "】");
}
return true;
}catch (Exception e){
throw new BadRequestException(messge + "In vivo detection identification"); }}Copy the code
package org.jeecg.modules.exam.utils.face;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.facebody.model.v20191230.*;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.tzf.BadRequestException;
import org.jeecg.modules.exam.utils.face.entity.Results;
import org.springframework.beans.factory.annotation.Value;
import java.util.ArrayList;
import java.util.List;
/ * * *@author: admin *@date: Created in 2020/7/7 17:54 *@Time: 17:54
* @description: Face recognition *@modified By:
* @version: 1.0 $* /
@Slf4j
public class FaceRecognition {
@Value(value="${face.accessKeyId}")
private static String accessKeyId;
@Value(value="${face.secret}")
private static String secret;
CompareFace can detect faces in two images based on your input, and select the largest face in the two images for comparison to determine whether it is the same person. At the same time, return the rectangular frame coordinates of the two faces, the confidence of the comparison, and the confidence threshold of the different error rate. * * https://help.aliyun.com/document_detail/151891.html?spm=a2c4g.11186623.6.589.56705de3kX1diD@paramImageURLA ImageURL. Currently, only OSS links in Shanghai are supported@paramImageURLB ImageURL. Currently, only OSS links in Shanghai are supported */
public static Confidence FaceThan(String ImageURLA,String ImageURLB) {
DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secret);
IAcsClient client = new DefaultAcsClient(profile);
CompareFaceRequest request = new CompareFaceRequest();
request.setRegionId("cn-shanghai");
request.setImageURLA(ImageURLA);
request.setImageURLB(ImageURLB);
try {
CompareFaceResponse response = client.getAcsResponse(request);
Confidence confidence = new Confidence();
confidence.copy(response.getData().getConfidence(),
response.getData().getRectAList(),
response.getData().getRectBList(),
response.getData().getThresholds());
//System.out.println(new Gson().toJson(response));
return confidence;
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
log.error(e.getMessage());
}
return null;
}
/** * Video liveness detection * document address https://help.aliyun.com/document_detail/167847.html?spm=5176.12901015.0.i12901015.2932525cEVM3hb&accounttraceid=50ed0f85 458549a3aeed92836ee86a3fcdfe *@param VideoUrl
*/
public static Elements VideoVivoDetection(String VideoUrl) {
DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secret);
IAcsClient client = new DefaultAcsClient(profile);
DetectVideoLivingFaceRequest request = new DetectVideoLivingFaceRequest();
request.setRegionId("cn-shanghai");
request.setVideoUrl(VideoUrl);
try {
DetectVideoLivingFaceResponse response = client.getAcsResponse(request);
// System.out.println(response.getData().getElements().toString());
Elements elements = new Elements();
elements.copy(response.getData().getElements().get(0).getFaceConfidence(),
response.getData().getElements().get(0).getLiveConfidence(),
response.getData().getElements().get(0).getRect());
// System.out.println(new Gson().toJson(response));
return elements;
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
log.error(e.getMessage());
// System.out.println("ErrCode:" + e.getErrCode());
// System.out.println("ErrMsg:" + e.getErrMsg());
// System.out.println("RequestId:" + e.getRequestId());
}
return null;
}
/ * * * photo live testing address https://help.aliyun.com/document_detail/155006.html?spm=a2c4g.11186623.6.587.75876c6cq8RdaW * * document@paramPhotoUrl Photo address *@paramMessge Prompt message *@return* /
public static Results VideoVivoDetectionPhoto(String PhotoUrl,String messge) {
DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secret);
IAcsClient client = new DefaultAcsClient(profile);
DetectLivingFaceRequest request = new DetectLivingFaceRequest();
request.setRegionId("cn-shanghai");
List<DetectLivingFaceRequest.Tasks> tasksList = new ArrayList<DetectLivingFaceRequest.Tasks>();
DetectLivingFaceRequest.Tasks tasks1 = new DetectLivingFaceRequest.Tasks();
tasks1.setImageURL(PhotoUrl);
tasksList.add(tasks1);
request.setTaskss(tasksList);
try {
DetectLivingFaceResponse response = client.getAcsResponse(request);
Results results = new Results();
results.copy(response.getData().getElements().get(0).getResults().get(0).getLabel(),
response.getData().getElements().get(0).getResults().get(0).getRate(),
response.getData().getElements().get(0).getResults().get(0).getSuggestion());
if("liveness".equals(results.getLabel())){
throw new BadRequestException(messge + "Do not upload remade photos.");
}
if("review".equals(results.getSuggestion())){
throw new BadRequestException(messge + "This photo may be from a remake. Please upload it again.");
}
if("block".equals(results.getSuggestion())){
throw new BadRequestException(messge + "This photo is probably from a remake. Please upload it again.");
}
return results;
} catch (ServerException e) {
e.printStackTrace();
log.error("Server exception {}" + e.getMessage());
} catch (ClientException e) {// The client is abnormal
e.printStackTrace();
log.error("Client exception exception message {} ErrCode {} \nErrMsg{} \n RequestId{}" , e.getMessage(), e.getErrCode(), e.getErrMsg(), e.getRequestId());
} catch (BadRequestException e) {
log.error("Custom exception");
return null;
}
return null;
}
/** * address translation *@param URL
*/
public static String AddressTranslation(String URL) {
//String file = /home/admin/file/1.jpg or upload locally
//String file = "https://fuss10.elemecdn.com/5/32/c17416d77817f2507d7fbdf15ef22jpeg.jpeg";
try {
FileUtils fileUtils = FileUtils.getInstance(accessKeyId,secret);
String ossurl = fileUtils.upload(URL);
System.out.println(ossurl);
return ossurl;
}catch (ClientException e){
System.out.println(e.getMessage());
}catch (IOException e){
System.out.println(e.getMessage());
}
return null; }}Copy the code
package org.jeecg.modules.exam.utils.face;
import cn.hutool.core.io.FileUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.util.ResourceUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/ * * *@author: admin *@date: Created in 2020/7/9 11:28 *@Time: so *@description: Video capture *@modified By:
* @version: 1.0 $* /
public class VideoCapture {
// public static void main(String[] args) {
// String videoPath = "C:\\Users\\admin\\Pictures\\rz\\hz.mp4";
//
/ / / * *
// * 1
// * 2
// * 3
/ / * /
// Elements elements = FaceRecognition.VideoVivoDetection(videoPath);
/ / System. Out. Println (" face of confidence -- -- -- -- -- -- -- -- -- -- -- -- -- -- "+ elements. GetFaceConfidence ());
/ / System. Out. Println (" living confidence -- -- -- -- -- -- -- -- -- -- -- -- -- -- "+ elements. GetLiveConfidence ());
/ / System. Out. Println (" detect the human face location -- -- -- -- -- -- -- -- -- -- -- -- -- -- "+ elements. The getRect ());
/ / System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- living through ");
/ / System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- living through ");
// File video = null;
// try {
// video = ResourceUtils.getFile(videoPath);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
/ /}
// for (int i = 0; i < 50; i++) {
// String picPath = "C:\\Users\\admin\\Pictures\\rz\\"+ i +".jpg";
// getVideoPic(video, picPath,i*10);
/ /}
// long duration = getVideoDuration(video);
// System.out.println("\n\n\n\n\n\nvideoDuration ************************************** " + duration);
// System.out.println("\n\n\n\n\n\nvideoDuration ************************************** " + duration);
/ / System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- video capture complete ");
// String picPath = "C:\\Users\\admin\\Pictures\\rz\\20200709115814.png";
// for (int i = 0; i < 1; i++) {
// String picPath1 = "C:\\Users\\admin\\Pictures\\rz\\"+ i +".jpg";
/ / System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- compared to address 1 "+ picPath1 +" \ n 】 【 picPath "+ +") ");
// FaceRecognition.FaceThan(picPath1,picPath);
/ /}
/ / System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- similarity certification by ");
//
//
//
/ /}
/** * Capture the video to get the picture of the specified frame **@paramVideo Source video file *@paramPicPath Path where the screenshot is stored */
public static void getVideoPic(File video, String picPath,int i) {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
try {
ff.start();
// Capture the middle frame (depending on the actual situation)
// int i = 0;
int length = ff.getLengthInFrames();
int middleFrame = length / 2;
Frame frame = null;
while (i < length) {
frame = ff.grabFrame();
if((i > middleFrame) && (frame.image ! =null)) {
break;
}
i++;
}
// Capture the frame image
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage srcImage = converter.getBufferedImage(frame);
int srcImageWidth = srcImage.getWidth();
int srcImageHeight = srcImage.getHeight();
// Scale the screenshot equally (thumbnail)
int width = 480;
int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0.0.null);
File picFile = new File(picPath);
ImageIO.write(thumbnailImage, "jpg", picFile);
ff.stop();
// Delete temporary files
FileUtil.del(picFile);
} catch(IOException e) { e.printStackTrace(); }}/** * Gets the video duration, in seconds *@paramVideo Source video file *@returnDuration (s) */
public static long getVideoDuration(File video) {
long duration = 0L;
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
try {
ff.start();
duration = ff.getLengthInTime() / (1000 * 1000);
ff.stop();
} catch (FrameGrabber.Exception e) {
e.printStackTrace();
}
return duration;
}
/** ** capture the video to get the picture of the specified frame **@paramVideo Source video file *@paramPicPath Path where the screenshot is stored *@paramThe I frame * /
public static String getVideoPic(File video, String picPath,int i) {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
try {
ff.start();
// Capture the middle frame (depending on the actual situation)
// int i = 0;
int length = ff.getLengthInFrames();
int middleFrame = length / 2;
Frame frame = null;
while (i < length) {
frame = ff.grabFrame();
if((i > middleFrame) && (frame.image ! =null)) {
break;
}
i++;
}
// Capture the frame image
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage srcImage = converter.getBufferedImage(frame);
int srcImageWidth = srcImage.getWidth();
int srcImageHeight = srcImage.getHeight();
// Scale the screenshot equally (thumbnail)
int width = 480;
int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0.0.null);
File picFile = new File( "/tang/file/upFiles/"+ picPath + "/" + StringUtils.UUIDNanoTime() + ".jpg");
if(! picFile.exists()) { picFile.mkdirs(); }//File picFile = new File(LinuxUpload + "\\"+ picPath + "\\" + StringUtils.UUIDNanoTime() + ".jpg");
ImageIO.write(thumbnailImage, "jpg", picFile);
ff.stop();
String OssUrl = getOssUrl(picFile,picPath);// Address of Aliyun
// Delete temporary files
FileUtil.del(picFile);
return OssUrl;
} catch (IOException e) {
e.printStackTrace();
log.info("Video capture exception" + e.getMessage());
}catch (Exception e) {
e.printStackTrace();
log.info("Video capture upload exception" + e.getMessage());
}
return null; }}Copy the code
Video processing
Rely on
<! -- aliyun oss --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> The < version > 3.6.0 < / version > < / dependency >Copy the code
www.alibabacloud.com/help/zh/doc…
package org.jeecg.modules.exam.controller;
import com.aliyun.oss.model.LiveChannelInfo;
import com.aliyun.oss.model.LiveChannelListing;
import com.aliyun.oss.model.LiveRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.tzf.ResponseEntityT;
import org.jeecg.modules.exam.utils.LiveChannelAdd;
import org.jeecg.modules.exam.utils.LiveChannelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/ * * *@author: admin *@date: Created in 2020/9/10 16:43 *@Time: behold *@description: LiveChannel tool class *@modified By:
* @version: 1.0 $* /
@Slf4j
@Controller
@RequestMapping("/oss/LiveChannel")
@ Api (tags = "LiveChannel tools")
public class LiveChannelController {
@ResponseBody
@GetMapping("/createLiveChannel")
@apiOperation (value=" create LiveChannel", notes="")
public ResponseEntityT<LiveChannelAdd> createLiveChannel(@RequestParam(name = "liveChannelName") String liveChannelName) {
return ResponseEntityT.ok(LiveChannelUtils.createLiveChannel(liveChannelName));
}
@ResponseBody
@GetMapping("/listLiveChannels")
@apiOperation (value=" LiveChannel", notes="")
public ResponseEntityT<LiveChannelListing> listLiveChannels(a) {
return ResponseEntityT.ok(LiveChannelUtils.listLiveChannels());
}
// @ResponseBody
// @GetMapping("/deleteLiveChannel")
// @apiOperation (value=" delete LiveChannel", notes="")
// public ResponseEntityT deleteLiveChannel(@RequestParam(name = "liveChannelName") String liveChannelName) {
// LiveChannelUtils.deleteLiveChannel(liveChannelName);
// return ResponseEntityT.ok();
/ /}
@ResponseBody
@GetMapping("/setLiveChannelStatus")
@apiOperation (value=" Set LiveChannel status ", notes=" stU status enabled disabled ")
public ResponseEntityT setLiveChannelStatus(@RequestParam(name = "liveChannelName") String liveChannelName, String stu) {
LiveChannelUtils.setLiveChannelStatus(liveChannelName,stu);
return ResponseEntityT.ok("Operation successful");
}
@ResponseBody
@GetMapping("/getLiveChannelInfo")
@apiOperation (value=" get LiveChannel configuration information ")
public ResponseEntityT<LiveChannelInfo> getLiveChannelInfo(@RequestParam(name = "liveChannelName") String liveChannelName) {
return ResponseEntityT.ok(LiveChannelUtils.getLiveChannelInfo(liveChannelName));
}
@ResponseBody
@GetMapping("/postVodPlaylist")
@apiOperation (value=" Generate LiveChannel playlist ")
publicResponseEntityT<? > getLiveChannelInfo(@RequestParam(name = "liveChannelName") String liveChannelName, String playListName, String start, String end) {
LiveChannelUtils.postVodPlaylist(liveChannelName,playListName, start, end);
return ResponseEntityT.ok("Generated successfully");
}
@ResponseBody
@GetMapping("/getVodPlaylist")
@apiOperation (value=" Check LiveChannel playlist ")
publicResponseEntityT<? > getVodPlaylist(@RequestParam(name = "liveChannelName") String liveChannelName, String start, String end) {
LiveChannelUtils.getVodPlaylist(liveChannelName, start, end);
return ResponseEntityT.ok("Generated successfully");
}
@ResponseBody
@GetMapping("/getLiveChannelHistory")
@apiOperation (value=" get the flow record from LiveChannel ")
public ResponseEntityT<List<LiveRecord>> getLiveChannelHistory(@RequestParam(name = "liveChannelName") String liveChannelName) {
returnResponseEntityT.ok(LiveChannelUtils.getLiveChannelHistory(liveChannelName)); }}Copy the code
package org.jeecg.modules.exam.utils;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.jeecg.common.util.tzf.BadRequestException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/ * * *@author: admin *@date: Created in 2020/9/10 15:48 *@Time: as *@description: *@modified By:
* @version: $
*/
public class LiveChannelUtils {
private static String endpoint = "oss-cn-shanghai.aliyuncs.com";/ / in Shanghai
private static String accessKeyId = "XXXXXXXXXXXXXXXXXXXX";
private static String accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static String bucketName = "XXXXX-video";
/** * create LiveChannel */
public static LiveChannelAdd createLiveChannel(String liveChannelName) {
LiveChannelAdd liveChannelAdds = new LiveChannelAdd();
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
CreateLiveChannelRequest request = new CreateLiveChannelRequest(bucketName,
liveChannelName, "desc", LiveChannelStatus.Enabled, new LiveChannelTarget());
CreateLiveChannelResult result = oss.createLiveChannel(request);
// // Obtain the traffic address
// List
publishUrls = result.getPublishUrls();
// for (String item : publishUrls) {
// publishUrl.add(item);
System.out.println("Obtain the push stream address ------------------------------");
System.out.println(item);
/ /}
// // Obtain the broadcast address.
// List
playUrls = result.getPlayUrls();
// for (String item : playUrls) {
// playUrl.add(item);
System.out.println("Get play address ------------------------------");
System.out.println(item);
/ /}
liveChannelAdds.setPublishUrls(result.getPublishUrls());
liveChannelAdds.setPlayUrls(result.getPlayUrls());
oss.shutdown();
return liveChannelAdds;
}
/** * LiveChannel */
public static LiveChannelListing listLiveChannels(a) {
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ListLiveChannelsRequest request = new ListLiveChannelsRequest(bucketName);
LiveChannelListing liveChannelListing = oss.listLiveChannels(request);
System.out.println("Listed LiveChannel -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
System.out.println(JSON.toJSONString(liveChannelListing));
oss.shutdown();
return liveChannelListing;
}
// /**
// * 删除 LiveChannel
/ / * /
// public static void deleteLiveChannel(String liveChannelName) {
// // Create an OSSClient instance.
// OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// LiveChannelGenericRequest request = new LiveChannelGenericRequest(bucketName, liveChannelName);
// try {
// oss.deleteLiveChannel(request);
// } catch (OSSException ex) {
// ex.printStackTrace();
// throw new BadRequestException(" failed to close the channel, "+ ex.getMessage());
// } catch (ClientException ex) {
// ex.printStackTrace();
// throw new BadRequestException(" failed to close the channel, "+ ex.getMessage());
// } finally {
// oss.shutdown();
/ /}
/ /}
/** * Set the LiveChannel state */
public static void setLiveChannelStatus(String liveChannelName,String stu) {
//String liveChannelName = "<yourLiveChannelName>";
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
if("enabled".equals(stu)){
oss.setLiveChannelStatus(bucketName, liveChannelName, LiveChannelStatus.Enabled );
}
if("disabled".equals(stu)){ oss.setLiveChannelStatus(bucketName, liveChannelName, LiveChannelStatus.Disabled ); }}catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}/** * Get LiveChannel configuration information */
public static LiveChannelInfo getLiveChannelInfo(String liveChannelName) {
//String liveChannelName = "<yourLiveChannelName>";
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
LiveChannelInfo liveChannelInfo = oss.getLiveChannelInfo(bucketName, liveChannelName);
System.out.println(JSON.toJSONString(liveChannelInfo));
oss.shutdown();
return liveChannelInfo;
}
/** * Generate LiveChannel playlist *@param liveChannelName
* @param playListName
* @param start
* @param end
*/
public static void postVodPlaylist(String liveChannelName,String playListName,String start,String end) {
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);/ / the 2019-06-27 23:00:00 ""
long endTIme = getUnixTimestamp(end);/ / the 2019-06-28 23:00:00 ""
try {
oss.generateVodPlaylist(bucketName, liveChannelName, playListName, startTime, endTIme);
} catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}public static void postVodPlaylistT(String liveChannelName,String playListName,String start,String end) {
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);/ / the 2019-06-27 23:00:00 ""
long endTIme = getUnixTimestamp(end);/ / the 2019-06-28 23:00:00 ""
try {
oss.generateVodPlaylist(bucketName, liveChannelName, playListName, startTime, endTIme);
} catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}/** * Generate LiveChannel playlist *@param liveChannelName
* @param playListName
* @param startTime
* @param endTIme
*/
public static void postVodPlaylist(String liveChannelName,String playListName,long startTime,long endTIme) {
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
oss.generateVodPlaylist(bucketName, liveChannelName, playListName, startTime, endTIme);
} catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}private static long getUnixTimestamp(String time) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(time);
return date.getTime() / 1000;
} catch (ParseException e) {
e.printStackTrace();
return 0; }}/** * View the LiveChannel playlist *@param liveChannelName
* @param start
* @param end
*/
public static void getVodPlaylist(String liveChannelName,String start,String end) {
// String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// // The main account AccessKey of Alibaba Cloud has access rights to all apis, which is highly risky.
/ / / / it is highly recommended that you create and use RAM account for API access or daily operations, please go to https://ram.console.aliyun.com to create RAM account.
// String accessKeyId = "
";
// String accessKeySecret = "
";
// String liveChannelName = "
";
// String bucketName = "
";
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);/ / the 2019-06-27 23:00:00 ""
long endTIme = getUnixTimestamp(end);/ / the 2019-06-28 23:00:00 ""
try {
OSSObject ossObject = oss.getVodPlaylist(bucketName, liveChannelName, startTime, endTIme);
System.out.println(ossObject.toString());
} catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}/** * Get LiveChannel push record */
public static List<LiveRecord> getLiveChannelHistory(String liveChannelName) {
try {
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
List<LiveRecord> list = oss.getLiveChannelHistory(bucketName, liveChannelName);
System.out.println("----- push flow record -----");
System.out.println(JSON.toJSONString(list));
System.out.println("----- push flow record -----");
oss.shutdown();
return list;
}catch (Exception e){
throw new BadRequestException("Get exception -"+ e.getMessage()); }}public static void main(String[] args) {
//getLiveChannelHistory("online_examination");
long s = Long.valueOf("1599793969310");
long e = Long.valueOf("1599793986570");
LiveChannelAdd liveChannelAdd = createLiveChannel("online-examination");
System.out.println(liveChannelAdd.getPlayUrls());
System.out.println(liveChannelAdd.getPublishUrls());
//listLiveChannels();
// postVodPlaylist("online_examination","playlist.m3u8","2020-09-10 20:44:59","2020-09-11 15:45:17");
//getLiveChannelHistory("online-examination");
// listLiveChannels();
}
/** * Generate LiveChannel playlist *@param liveChannelName
*/
public static void postVodPlaylist(String liveChannelName) {
//String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// AccessKey, the main account of Aliyun, has access to all apis, which is highly risky.
/ / it is highly recommended that you create and use RAM account for API access or daily operations, please go to https://ram.console.aliyun.com to create RAM account.
// String accessKeyId = "
";
// String accessKeySecret = "
";
// String liveChannelName = "
";
// String bucketName = "
";
String playListName = "playlist.m3u8";
// Create an OSSClient instance.
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp("The 2020-09-10 23:00:00");//
long endTIme = getUnixTimestamp("The 2020-09-11 23:00:00");//
try {
oss.generateVodPlaylist(bucketName, liveChannelName, playListName, startTime, endTIme);
} catch (OSSException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} catch (ClientException ex) {
System.out.println(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
throw new BadRequestException(ex.getErrorCode().concat(",").concat(ex.getErrorMessage()));
} finally{ oss.shutdown(); }}}Copy the code
Front-end UNI-app push stream calls
slightly