package com.netsdk.demo.customize; import com.netsdk.demo.util.CaseMenu; import com.netsdk.lib.NativeString; import com.netsdk.lib.NetSDKLib; import com.netsdk.lib.ToolKits; import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack; import com.netsdk.lib.enumeration.EM_REASON_TYPE; import com.netsdk.lib.structure.*; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.IntByReference; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import static com.netsdk.lib.NetSDKLib.CtrlType.CTRLTYPE_CTRL_START_PLAYAUDIO; import static com.netsdk.lib.NetSDKLib.CtrlType.CTRLTYPE_CTRL_STOP_PLAYAUDIO; import static com.netsdk.lib.Utils.getOsPrefix; public class RemoteSpeakPlayDemo { // SDk对象初始化 public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE; public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE; /** * 选择通道 */ private int channelId = -1;// 逻辑通道 // 判断是否初始化 private static boolean bInit = false; // 判断log是否打开 private static boolean bLogOpen = false; // 设备信息 private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex(); // 登录句柄 private NetSDKLib.LLong loginHandle = new NetSDKLib.LLong(0); // 智能事件订阅句柄 private NetSDKLib.LLong m_attachHandle = new NetSDKLib.LLong(0); //实现断线重连静态单例 public static class DefaultDisconnectCallback implements NetSDKLib.fDisConnect { private static volatile DefaultDisconnectCallback INSTANCE; private DefaultDisconnectCallback() {} public static DefaultDisconnectCallback getINSTANCE() { if (INSTANCE == null) { synchronized (DefaultDisconnectCallback.class){ if (INSTANCE == null){ INSTANCE = new DefaultDisconnectCallback(); } } } return INSTANCE; } @Override public void invoke(NetSDKLib.LLong lLoginID, String pchDVRIP, int nDVRPort, Pointer dwUser) { System.out.printf("Device[%s] Port[%d] DisConnected!\n", pchDVRIP, nDVRPort); } } // 回调函数需要是静态的,防止被系统回收 // 断线回调 private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE(); // 重连回调 private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE(); //订阅句柄 NetSDKLib.LLong lAttachHandle = new NetSDKLib.LLong(0); // 编码格式 public static String encode; static { String osPrefix = getOsPrefix(); if (osPrefix.toLowerCase().startsWith("win32-amd64")) { encode = "GBK"; } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) { encode = "UTF-8"; } } /** * 按照指定格式,获取当前时间 */ public static String getDate() { SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDate.format(new Date()).replaceAll("[^0-9]", "-"); } /** * 初始化SDK库 */ public static boolean initSdk() { bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时,初始化一次 if (!bInit) { System.out.println("Initialize SDK failed"); return false; } // 配置日志 enableLog(); // 设置断线重连回调接口, 此操作为可选操作,但建议用户进行设置 netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null); // 设置登录超时时间和尝试次数,可选 // 登录请求响应超时时间设置为3S int waitTime = 3000; //单位为ms // 登录时尝试建立链接 1 次 int tryTimes = 1; // 设置连接设备超时时间和尝试次数 netsdk.CLIENT_SetConnectTime(waitTime, tryTimes); // 设置更多网络参数, NET_PARAM 的nWaittime , nConnectTryNum 成员与 CLIENT_SetConnectTime // 接口设置的登录设备超时时间和尝试次数意义相同,可选 NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM(); // 登录时尝试建立链接的超时时间 netParam.nConnectTime = 10000; // 设置子连接的超时时间 netParam.nGetConnInfoTime = 3000; //设置登陆网络环境 netsdk.CLIENT_SetNetworkParam(netParam); return true; } /** * 打开 sdk log */ private static void enableLog() { // SDK全局日志打印信息 NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO(); //设置日志路径 File path = new File("sdklog/"); //判断日志路径是否存在,若不存在则创建 if (!path.exists()){ path.mkdir(); } // 这里的log保存地址依据实际情况自己调整 String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + getDate() + ".log"; //日志输出策略,0:输出到文件(默认); 1:输出到窗口, setLog.nPrintStrategy = 0; //是否重设日志路径, 取值0否 ,1是 setLog.bSetFilePath = 1; //日志路径(默认"./sdk_log/sdk_log.log") byte[] szLogFilePath = setLog.szLogFilePath; //自定义log保存地址,将数据logPath数据copy到LOG_SET_PRINT_INFO-->szLogFilePath变量中 System.arraycopy(logPath.getBytes(), 0, szLogFilePath, 0, logPath.getBytes().length); //是否重设日志打印输出策略 取值0否 ,1是 setLog.bSetPrintStrategy = 1; // 打开日志功能 bLogOpen = netsdk.CLIENT_LogOpen(setLog); if (!bLogOpen){ System.err.println("Failed to open NetSDK log "+ ToolKits.getErrorCode()); }else { System.out.println("Success to open NetSDK log "); } } /** * 高安全登录 */ public void loginWithHighLevel() { // 输入结构体参数 NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() { { // IP szIP = m_strIpAddr.getBytes(); // 端口 nPort = m_nPort; // 用户名 szUserName = m_strUser.getBytes(); // 密码 szPassword = m_strPassword.getBytes(); } }; // 登录的输出结构体参数 NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY(); // 高安全级别登陆 loginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam); if (loginHandle.longValue() == 0) { //登陆失败 System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort, ToolKits.getErrorCode()); } else { //登陆成功 // 获取设备信息 deviceInfo = pstOutParam.stuDeviceInfo; System.out.printf("Login Success Device Address[%s] 设备包含[%d]个通道 \n",m_strIpAddr,deviceInfo.byChanNum); } } /** * 停止侦听智能事件 */ public void DetachEventRealLoadPic() { if (m_attachHandle.longValue() != 0) { netsdk.CLIENT_StopLoadPic(m_attachHandle); System.out.println("CLIENT_StopLoadPic Success"); } } /** * 退出 */ public void logOut() { //判断是否已登录 if (loginHandle.longValue() != 0) { netsdk.CLIENT_Logout(loginHandle); System.out.println("LogOut Success"); } } /** * 清理sdk环境并退出 */ public static void cleanAndExit() { //判断log是否打开 if (bLogOpen) { // 关闭sdk日志打印 netsdk.CLIENT_LogClose(); } // 进程关闭时,调用一次 netsdk.CLIENT_Cleanup(); System.exit(0); } /** * 初始化测试 */ public void initTest() { initSdk(); this.loginWithHighLevel(); } /** * 结束测试 */ public void endTest() { System.out.println("End Test"); this.logOut(); // 登出设备 System.out.println("See You..."); cleanAndExit(); // 清理资源并退出 } public void runTest() { System.out.println("Run Test"); CaseMenu menu = new CaseMenu(); menu.addItem(new CaseMenu.Item(this, "获取设备音频能力", "getDeviceAudioCap")); menu.addItem(new CaseMenu.Item(this, "音频文件预上传", "preAudioUpload")); menu.addItem(new CaseMenu.Item(this, "上传音频文件", "audioUpload")); menu.addItem(new CaseMenu.Item(this, "获取音频文件列表", "audioList")); menu.addItem(new CaseMenu.Item(this, "开始播放音频文件", "audioPlayStart")); menu.addItem(new CaseMenu.Item(this, "停止播放音频文件", "audioPlayStop")); menu.addItem(new CaseMenu.Item(this, "删除音频文件", "audioRemove")); menu.run(); } // 配置登陆地址,端口,用户名,密码 private String m_strIpAddr = "172.13.76.116"; private int m_nPort = 37777; private String m_strUser = "admin"; private String m_strPassword = "admin111"; public static void main(String[] args) { RemoteSpeakPlayDemo demo=new RemoteSpeakPlayDemo(); demo.initTest(); demo.runTest(); demo.endTest(); } private List audioPaths; private List destPaths; private List audios; int nChannel = 0;//通道号 // 测试时可以进入设备->相机设置->音频->报警声音—>下载 private final String srcFile = "D:\\download\\alarm1.wav"; public RemoteSpeakPlayDemo(){ audioPaths=new ArrayList<>(); destPaths=new ArrayList<>(); audios=new ArrayList<>(); } /** * 获取设备音频能力:查看可上传路径,支持的音频格式 */ public void getDeviceAudioCap(){ String audioCap=NetSDKLib.CFG_CAP_CMD_SPEAK; NET_CFG_CAP_SPEAK speak=new NET_CFG_CAP_SPEAK(); if(getDevConfig(loginHandle,audioCap,speak,-1)){ destPaths.clear(); System.out.println("播放路径个数: "+speak.nAudioPlayPathNum); for (int i = 0; i < speak.nAudioPlayPathNum; i++) { System.out.println("is support upload: "+speak.stuAudioPlayPath[i].bSupportUpload+",path: "+new String(speak.stuAudioPlayPath[i].szPath)+",max file upload number:"+speak.stuAudioPlayPath[i].nMaxFileUploadNum+",max file upload size(kb): "+speak.stuAudioPlayPath[i].nMaxUploadFileSize/1024.0); if(speak.stuAudioPlayPath[i].bSupportUpload){ try { destPaths.add(new String(speak.stuAudioPlayPath[i].szPath, encode).trim()); }catch (Exception e){ e.getMessage(); } } if(!"".equals(new String(speak.stuAudioPlayPath[i].szPath).trim())){ try { audioPaths.add(new String(speak.stuAudioPlayPath[i].szPath,encode).trim()); }catch (Exception e){ e.getMessage(); } } } } } /** * 查询设备能力集 * @param loginHandle 登录句柄 * @param command 能力集命令 * @param structure 能力集的结构体 * @param channelID 通道号 * @return */ private boolean getDevConfig(NetSDKLib.LLong loginHandle, String command, Structure structure, int channelID){ boolean result=false; int error[] = {0}; int nBufferLen = 100*1024; byte[] strBuffer = new byte[nBufferLen]; result=netsdk.CLIENT_QueryNewSystemInfo(loginHandle,command,channelID,strBuffer,nBufferLen,new IntByReference(0),3000); if(result){ structure.write(); if(configsdk.CLIENT_ParseData(command,strBuffer,structure.getPointer(),structure.size(),null)){ structure.read(); }else{ System.out.println("Parse " + command + " Config Failed!"); } }else{ System.out.printf("Get %s Config Failed!Last Error = %s\n" , command , ToolKits.getErrorCode()); } return result; } /** * 音频文件预上传,校验该文件是否可以上传 */ public void preAudioUpload(){ NET_IN_PRE_UPLOAD_REMOTE_FILE inparam=new NET_IN_PRE_UPLOAD_REMOTE_FILE(); inparam.pszFileSrc=new File(srcFile).getAbsolutePath(); Scanner scanner=new Scanner(System.in); for (int i = 0; i < destPaths.size(); i++) { System.out.println(i+" : "+destPaths.get(i)); } System.out.println("please input the num to select the path to preupload: "); String destPath=destPaths.get(scanner.nextInt()); //要上传的路径,上传文件夹+文件名 inparam.pszFileDst=destPath+new File(srcFile).getName(); NET_OUT_PRE_UPLOAD_REMOTE_FILE outparam=new NET_OUT_PRE_UPLOAD_REMOTE_FILE(); boolean preUpload = netsdk.CLIENT_PreUploadRemoteFile(loginHandle,inparam,outparam,3000); if(preUpload){ // emType为0则没有问题 if(outparam.emType == 0){ System.out.println("can upload: "+outparam.bContinue2Upload); }else { System.out.println("can upload: "+outparam.bContinue2Upload+",reason:"+ EM_REASON_TYPE.getReason(outparam.emType)); } }else{ System.out.println("pre upload failed: "+ToolKits.getErrorCode()); } } /** * 上传音频文件 */ public void audioUpload(){ Scanner scanner=new Scanner(System.in); for (int i = 0; i < destPaths.size(); i++) { System.out.println(i+" : "+destPaths.get(i)); } System.out.println("please input the num to select the path to upload: "); String destPath = destPaths.get(scanner.nextInt()); //入参 NetSDKLib.NET_IN_UPLOAD_REMOTE_FILE uploadParam=new NetSDKLib.NET_IN_UPLOAD_REMOTE_FILE(); //要上传的文件 File file=new File(srcFile); String filePath=file.getAbsolutePath(); String fileName=file.getName(); //源文件的路径 uploadParam.pszFileSrc=new NativeString(filePath).getPointer(); //目标文件名称 uploadParam.pszFileDst=new NativeString(fileName).getPointer(); // 接口参数上的注释:目标文件夹路径:可为NULL, NULL时设备使用默认路径 //注意:如果为null,会使用默认路径,但使用默认路径上传会失败, // 需要先获取设备音频能力集,得到可上传的路径,并设置为目标文件夹路径 uploadParam.pszFolderDst=new NativeString(destPath).getPointer(); //文件分包大小(字节): 0表示不分包 uploadParam.nPacketLen=1024*2; NetSDKLib.NET_OUT_UPLOAD_REMOTE_FILE uploadOutParam=new NetSDKLib.NET_OUT_UPLOAD_REMOTE_FILE(); uploadParam.write(); boolean isUpload = netsdk.CLIENT_UploadRemoteFile(loginHandle,uploadParam,uploadOutParam,3000); uploadParam.read(); if(isUpload){ System.out.println("upload audio success!"); }else{ /** * 如果上传失败,请检查上传的文件大小,上传路径,上传格式 */ System.out.println("failed to upload audio.the error is "+ToolKits.getErrorCode()); } } /** * 获取音频文件列表 */ public void audioList(){ // 出参 NetSDKLib.NET_OUT_LIST_REMOTE_FILE stOut = new NetSDKLib.NET_OUT_LIST_REMOTE_FILE(); audios.clear(); for (String path:audioPaths) { NetSDKLib.SDK_REMOTE_FILE_INFO[] remoteFile = ToolKits.ListAudioFile(loginHandle, path, stOut); if(remoteFile != null) { System.out.println("nRetFileCount : " + stOut.nRetFileCount); for(int j = 0; j < stOut.nRetFileCount; j++) { try { System.out.println("szPath : " + new String(remoteFile[j].szPath, encode).trim()); audios.add(new String(remoteFile[j].szPath,encode).trim()); }catch (Exception e){ e.getMessage(); } } } else { System.err.println("ListRemoteFile Failed!" + ToolKits.getErrorCode()); } } } /** * 开始播放音频文件 */ public void audioPlayStart(){ for(int i=0;i