人臉識別(基於阿里雲)
阿新 • • 發佈:2020-12-08
技術標籤:JAVA阿里雲人臉識別視訊截圖LiveChannel工具LiveChannel推流通道
pom.xml
<!--人臉識別--> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.4.8</version> </dependency> <dependency> <groupId>com.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>
/** * 活體檢測 * @param fileUrl 照片 * @param messge 提示訊息 * @return */ public Boolean VideoVivoDetection(String fileUrl,String messge){ try { Results results = FaceRecognition.VideoVivoDetectionPhoto(fileUrl,messge); Float faceConfidence = Float.valueOf(sysUserRoleMapper.getSysDictItem("活體檢測-人臉的置信度"));//置信度 從資料字典表中讀取,實現動態調整 if(faceConfidence > results.getRate()){ throw new BadRequestException(messge + "【人臉的置信度】較低,系統要求置信度為:【" + faceConfidence + "】,本次檢查置信度【" + results.getRate() + "】"); } return true; }catch (Exception e){ throw new BadRequestException(messge + "活體檢測識別"); } }
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:人臉識別 * @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可以基於您輸入的兩張圖片,檢測兩張圖片中的人臉,並分別挑選兩張圖片中的最大人臉進行比較,判斷是否為同一人。同時返回這兩個人臉的矩形框座標、比對的置信度,以及不同誤識率的置信度閾值。 * https://help.aliyun.com/document_detail/151891.html?spm=a2c4g.11186623.6.589.56705de3kX1diD * @param ImageURLA 圖片URL地址。當前僅支援上海地域的OSS連結 * @param ImageURLB 圖片URL地址。當前僅支援上海地域的OSS連結 */ 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; } /** * 視訊活體檢測 * 文件地址 https://help.aliyun.com/document_detail/167847.html?spm=5176.12901015.0.i12901015.2932525cEVM3hb&accounttraceid=50ed0f85458549a3aeed92836ee86a3fcdfe * @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; } /** * 照片活體檢測 * 文件地址 https://help.aliyun.com/document_detail/155006.html?spm=a2c4g.11186623.6.587.75876c6cq8RdaW * @param PhotoUrl 照片地址 * @param messge 提示訊息 * @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 + "請勿上傳翻拍照片"); } if("review".equals(results.getSuggestion())){ throw new BadRequestException(messge + "照片可能來自翻拍,請重新上傳"); } if("block".equals(results.getSuggestion())){ throw new BadRequestException(messge + "照片大概率來自翻拍,請重新上傳"); } return results; } catch (ServerException e) { e.printStackTrace(); log.error("伺服器異常 {}" + e.getMessage()); } catch (ClientException e) {//客戶端異常 e.printStackTrace(); log.error("客戶端異常 異常資訊{} ErrCode {} \nErrMsg{} \n RequestId{}" , e.getMessage(), e.getErrCode(), e.getErrMsg(), e.getRequestId()); } catch (BadRequestException e) { log.error("自定義異常"); return null; } return null; } /** * 地址轉換 * @param URL */ public static String AddressTranslation(String URL) { //String file = /home/admin/file/1.jpg 或者本地上傳 //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; } }
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: 11:28
* @description:視訊擷取
* @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("人臉的置信度--------------" + elements.getFaceConfidence());
// System.out.println("活體的置信度--------------" + elements.getLiveConfidence());
// System.out.println("檢測出的人臉位置--------------" + elements.getRect());
// System.out.println("------------------------------活體檢測通過");
// System.out.println("------------------------------活體檢測通過");
// 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("------------------------------視訊擷取完成");
// 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("------------------------------對比地址1【" + picPath1 + "】\n【" + picPath + "】");
// FaceRecognition.FaceThan(picPath1,picPath);
// }
// System.out.println("------------------------------相似度認證通過");
//
//
//
// }
/**
* 擷取視訊獲得指定幀的圖片
*
* @param video 源視訊檔案
* @param picPath 截圖存放路徑
*/
public static void getVideoPic(File video, String picPath,int i) {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
try {
ff.start();
// 擷取中間幀圖片(具體依實際情況而定)
// 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++;
}
// 擷取的幀圖片
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage srcImage = converter.getBufferedImage(frame);
int srcImageWidth = srcImage.getWidth();
int srcImageHeight = srcImage.getHeight();
// 對截圖進行等比例縮放(縮圖)
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();
//刪除臨時檔案
FileUtil.del(picFile);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 獲取視訊時長,單位為秒
* @param video 源視訊檔案
* @return 時長(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;
}
/**
*
* 擷取視訊獲得指定幀的圖片 *
* @param video 源視訊檔案
* @param picPath 截圖存放路徑
* @param i 幀
*/
public static String getVideoPic(File video, String picPath,int i) {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
try {
ff.start();
// 擷取中間幀圖片(具體依實際情況而定)
// 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++;
}
// 擷取的幀圖片
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage srcImage = converter.getBufferedImage(frame);
int srcImageWidth = srcImage.getWidth();
int srcImageHeight = srcImage.getHeight();
// 對截圖進行等比例縮放(縮圖)
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);//阿里雲地址
//刪除臨時檔案
FileUtil.del(picFile);
return OssUrl;
} catch (IOException e) {
e.printStackTrace();
log.info("視訊擷取異常" + e.getMessage());
}catch (Exception e) {
e.printStackTrace();
log.info("視訊擷取上傳異常" + e.getMessage());
}
return null;
}
}
視訊處理
依賴
<!-- aliyun oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.6.0</version>
</dependency>
https://www.alibabacloud.com/help/zh/doc-detail/44297.htm
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: 16:43
* @description:LiveChannel 工具類
* @modified By:
* @version: 1.0$
*/
@Slf4j
@Controller
@RequestMapping("/oss/LiveChannel")
@Api(tags="LiveChannel工具")
public class LiveChannelController {
@ResponseBody
@GetMapping("/createLiveChannel")
@ApiOperation(value="建立 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() {
return ResponseEntityT.ok(LiveChannelUtils.listLiveChannels());
}
// @ResponseBody
// @GetMapping("/deleteLiveChannel")
// @ApiOperation(value="刪除 LiveChannel", notes="")
// public ResponseEntityT deleteLiveChannel(@RequestParam(name = "liveChannelName") String liveChannelName) {
// LiveChannelUtils.deleteLiveChannel(liveChannelName);
// return ResponseEntityT.ok();
// }
@ResponseBody
@GetMapping("/setLiveChannelStatus")
@ApiOperation(value="設定 LiveChannel 狀態", notes=" stu 二種狀態 enabled disabled ")
public ResponseEntityT setLiveChannelStatus(@RequestParam(name = "liveChannelName") String liveChannelName, String stu) {
LiveChannelUtils.setLiveChannelStatus(liveChannelName,stu);
return ResponseEntityT.ok("操作成功");
}
@ResponseBody
@GetMapping("/getLiveChannelInfo")
@ApiOperation(value="獲取 LiveChannel 配置資訊")
public ResponseEntityT<LiveChannelInfo> getLiveChannelInfo(@RequestParam(name = "liveChannelName") String liveChannelName) {
return ResponseEntityT.ok(LiveChannelUtils.getLiveChannelInfo(liveChannelName));
}
@ResponseBody
@GetMapping("/postVodPlaylist")
@ApiOperation(value="生成 LiveChannel 播放列表")
public ResponseEntityT<?> getLiveChannelInfo(@RequestParam(name = "liveChannelName") String liveChannelName, String playListName, String start, String end) {
LiveChannelUtils.postVodPlaylist(liveChannelName,playListName, start, end);
return ResponseEntityT.ok("生成成功");
}
@ResponseBody
@GetMapping("/getVodPlaylist")
@ApiOperation(value=" 檢視 LiveChannel 播放列表")
public ResponseEntityT<?> getVodPlaylist(@RequestParam(name = "liveChannelName") String liveChannelName, String start, String end) {
LiveChannelUtils.getVodPlaylist(liveChannelName, start, end);
return ResponseEntityT.ok("生成成功");
}
@ResponseBody
@GetMapping("/getLiveChannelHistory")
@ApiOperation(value=" 獲取 LiveChannel 推流記錄")
public ResponseEntityT<List<LiveRecord>> getLiveChannelHistory(@RequestParam(name = "liveChannelName") String liveChannelName) {
return ResponseEntityT.ok(LiveChannelUtils.getLiveChannelHistory(liveChannelName));
}
}
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: 15:48
* @description:
* @modified By:
* @version: $
*/
public class LiveChannelUtils {
private static String endpoint = "oss-cn-shanghai.aliyuncs.com";//用shanghai的
private static String accessKeyId = "XXXXXXXXXXXXXXXXXXXX";
private static String accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static String bucketName = "XXXXX-video";
/**
* 建立 LiveChannel
*/
public static LiveChannelAdd createLiveChannel(String liveChannelName) {
LiveChannelAdd liveChannelAdds = new LiveChannelAdd();
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
CreateLiveChannelRequest request = new CreateLiveChannelRequest(bucketName,
liveChannelName, "desc", LiveChannelStatus.Enabled, new LiveChannelTarget());
CreateLiveChannelResult result = oss.createLiveChannel(request);
// //獲取推流地址
// List<String> publishUrls = result.getPublishUrls();
// for (String item : publishUrls) {
// publishUrl.add(item);
System.out.println("獲取推流地址------------------------------");
System.out.println(item);
// }
// //獲取播放地址。
// List<String> playUrls = result.getPlayUrls();
// for (String item : playUrls) {
// playUrl.add(item);
System.out.println("獲取播放地址------------------------------");
System.out.println(item);
// }
liveChannelAdds.setPublishUrls(result.getPublishUrls());
liveChannelAdds.setPlayUrls(result.getPlayUrls());
oss.shutdown();
return liveChannelAdds;
}
/**
* 列舉 LiveChannel
*/
public static LiveChannelListing listLiveChannels() {
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ListLiveChannelsRequest request = new ListLiveChannelsRequest(bucketName);
LiveChannelListing liveChannelListing = oss.listLiveChannels(request);
System.out.println("列舉 LiveChannel------------------------------");
System.out.println(JSON.toJSONString(liveChannelListing));
oss.shutdown();
return liveChannelListing;
}
// /**
// * 刪除 LiveChannel
// */
// public static void deleteLiveChannel(String liveChannelName) {
// // 建立 OSSClient 例項。
// 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("推流通道關閉失敗," + ex.getMessage());
// } catch (ClientException ex) {
// ex.printStackTrace();
// throw new BadRequestException("推流通道關閉失敗," + ex.getMessage());
// } finally {
// oss.shutdown();
// }
// }
/**
* 設定 LiveChannel 狀態
*/
public static void setLiveChannelStatus(String liveChannelName,String stu) {
//String liveChannelName = "<yourLiveChannelName>";
// 建立OSSClient例項。
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();
}
}
/**
* 獲取 LiveChannel 配置資訊
*/
public static LiveChannelInfo getLiveChannelInfo(String liveChannelName) {
//String liveChannelName = "<yourLiveChannelName>";
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
LiveChannelInfo liveChannelInfo = oss.getLiveChannelInfo(bucketName, liveChannelName);
System.out.println(JSON.toJSONString(liveChannelInfo));
oss.shutdown();
return liveChannelInfo;
}
/**
* 生成 LiveChannel 播放列表
* @param liveChannelName
* @param playListName
* @param start
* @param end
*/
public static void postVodPlaylist(String liveChannelName,String playListName,String start,String end) {
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);//"2019-06-27 23:00:00"
long endTIme = getUnixTimestamp(end);//"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) {
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);//"2019-06-27 23:00:00"
long endTIme = getUnixTimestamp(end);//"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();
}
}
/**
* 生成 LiveChannel 播放列表
* @param liveChannelName
* @param playListName
* @param startTime
* @param endTIme
*/
public static void postVodPlaylist(String liveChannelName,String playListName,long startTime,long endTIme) {
// 建立 OSSClient 例項。
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;
}
}
/**
* 檢視 LiveChannel 播放列表
* @param liveChannelName
* @param start
* @param end
*/
public static void getVodPlaylist(String liveChannelName,String start,String end) {
// String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// // 阿里雲主賬號 AccessKey 擁有所有 API 的訪問許可權,風險很高。
// // 強烈建議您建立並使用 RAM 賬號進行 API 訪問或日常運維,請登入 https://ram.console.aliyun.com 建立 RAM 賬號。
// String accessKeyId = "<yourAccessKeyId>";
// String accessKeySecret = "<yourAccessKeySecret>";
// String liveChannelName = "<yourLiveChannelName>";
// String bucketName = "<yourBucketName>";
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp(start);//"2019-06-27 23:00:00"
long endTIme = getUnixTimestamp(end);//"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();
}
}
/**
* 獲取 LiveChannel 推流記錄
*/
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("-----推流記錄-----");
System.out.println(JSON.toJSONString(list));
System.out.println("-----推流記錄-----");
oss.shutdown();
return list;
}catch (Exception e){
throw new BadRequestException("獲取異常-" + 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();
}
/**
* 生成 LiveChannel 播放列表
* @param liveChannelName
*/
public static void postVodPlaylist(String liveChannelName) {
//String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里雲主賬號 AccessKey 擁有所有 API 的訪問許可權,風險很高。
// 強烈建議您建立並使用 RAM 賬號進行 API 訪問或日常運維,請登入 https://ram.console.aliyun.com 建立 RAM 賬號。
// String accessKeyId = "<yourAccessKeyId>";
// String accessKeySecret = "<yourAccessKeySecret>";
// String liveChannelName = "<yourLiveChannelName>";
// String bucketName = "<yourBucketName>";
String playListName = "playlist.m3u8";
// 建立 OSSClient 例項。
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
long startTime = getUnixTimestamp("2020-09-10 23:00:00");//
long endTIme = getUnixTimestamp("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();
}
}
}
前端uni-app推流呼叫
略